Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 123f3e6e2b | |||
| baaeb6b027 | |||
| 2537284372 | |||
| 76f75192d5 | |||
| 6156c66a20 | |||
| 7f4846a2d3 | |||
| e44bb8eca4 | |||
| 434e3c3af7 | |||
| b66d4da5d7 | |||
| 7b3a79b1b0 | |||
| c99d466b75 |
478
Cargo.lock
generated
478
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
1
TODO
1
TODO
@@ -16,6 +16,7 @@ scaling
|
|||||||
field could be best solution so redrawing stuff isn't needed & you can specify both as user
|
field could be best solution so redrawing stuff isn't needed & you can specify both as user
|
||||||
|
|
||||||
WidgetRef<W> or smth instead of Id
|
WidgetRef<W> or smth instead of Id
|
||||||
|
fyi this is not the same as what was just implemented
|
||||||
enum that's either an Id or an actual concrete instance of W
|
enum that's either an Id or an actual concrete instance of W
|
||||||
painter takes them in instead of (or in addition to) id
|
painter takes them in instead of (or in addition to) id
|
||||||
then type wrapper widgets to contain them
|
then type wrapper widgets to contain them
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
use crate::{HasUi, StateLike, WidgetIdFn, WidgetLike, WidgetRef};
|
|
||||||
|
|
||||||
pub trait WidgetAttr<State, W: ?Sized> {
|
|
||||||
type Input;
|
|
||||||
fn run(state: &mut State, id: WidgetRef<W>, input: Self::Input);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait Attrable<State, W: ?Sized, Tag> {
|
|
||||||
fn attr<A: WidgetAttr<State, W>>(self, input: A::Input) -> impl WidgetIdFn<State, W>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: HasUi + StateLike<State>, WL: WidgetLike<State, Tag>, Tag>
|
|
||||||
Attrable<State, WL::Widget, Tag> for WL
|
|
||||||
{
|
|
||||||
fn attr<A: WidgetAttr<State, WL::Widget>>(
|
|
||||||
self,
|
|
||||||
input: A::Input,
|
|
||||||
) -> impl WidgetIdFn<State, WL::Widget> {
|
|
||||||
|state| {
|
|
||||||
let id = self.add(state);
|
|
||||||
A::run(state, id, input);
|
|
||||||
id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
use crate::{HasEvents, HasState, HasUi, StateLike, Ui, Widget, WidgetRef};
|
|
||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
|
|
||||||
pub struct EventCtx<'a, State, Data> {
|
|
||||||
pub state: &'a mut State,
|
|
||||||
pub data: &'a mut Data,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct EventIdCtx<'a, State, Data, W: ?Sized> {
|
|
||||||
pub widget: WidgetRef<W>,
|
|
||||||
pub state: &'a mut State,
|
|
||||||
pub data: &'a mut Data,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: HasUi, Data, W: ?Sized> Deref for EventIdCtx<'_, State, Data, W> {
|
|
||||||
type Target = State;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
self.state
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: HasUi, Data, W: ?Sized> DerefMut for EventIdCtx<'_, State, Data, W> {
|
|
||||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
||||||
self.state
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: HasUi, Data, W: Widget> EventIdCtx<'_, State, Data, W> {
|
|
||||||
pub fn widget(&mut self) -> &mut W {
|
|
||||||
&mut self.state.get_mut()[self.widget]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: HasUi, Data, W: Widget> HasUi for EventIdCtx<'_, State, Data, W> {
|
|
||||||
fn get(&self) -> &Ui {
|
|
||||||
self.state.ui()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mut(&mut self) -> &mut Ui {
|
|
||||||
self.state.ui_mut()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: HasUi, Data, W: Widget> HasState for EventIdCtx<'_, State, Data, W> {
|
|
||||||
type State = State;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: HasEvents<State = State>, Data, W: Widget> HasEvents
|
|
||||||
for EventIdCtx<'_, State, Data, W>
|
|
||||||
{
|
|
||||||
fn get(&self) -> &super::EventManager<Self::State> {
|
|
||||||
self.state.events()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mut(&mut self) -> &mut super::EventManager<Self::State> {
|
|
||||||
self.state.events_mut()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State, Data, W: Widget> StateLike<State> for EventIdCtx<'_, State, Data, W> {
|
|
||||||
fn as_state(&mut self) -> &mut State {
|
|
||||||
self.state
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// fn test() {
|
|
||||||
// use crate::*;
|
|
||||||
// struct ClientRsc;
|
|
||||||
// impl<State, Data> HasUi for EventCtx<'_, State, Data> {
|
|
||||||
// fn get(&self) -> &Ui {
|
|
||||||
// todo!()
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// fn get_mut(&mut self) -> &mut Ui {
|
|
||||||
// todo!()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// fn on(_: impl for<'a> EventFn<ClientRsc, &'a mut i32>) {}
|
|
||||||
//
|
|
||||||
// pub trait WidgetLike<State: HasUi, Tag>: Sized {
|
|
||||||
// type Widget: Widget + ?Sized + std::marker::Unsize<dyn Widget>;
|
|
||||||
//
|
|
||||||
// fn add(self, state: &mut State) -> WidgetHandle<Self::Widget>;
|
|
||||||
//
|
|
||||||
// fn with_id<W2>(
|
|
||||||
// self,
|
|
||||||
// f: impl FnOnce(&mut State, WidgetHandle<Self::Widget>) -> WidgetHandle<W2>,
|
|
||||||
// ) -> impl WidgetIdFn<State, W2> {
|
|
||||||
// move |state| {
|
|
||||||
// let id = self.add(state);
|
|
||||||
// f(state, id)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// fn set_root(self, state: &mut State) {
|
|
||||||
// state.get_mut().root = Some(self.add(state));
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// fn handles(self, state: &mut State) -> WidgetHandles<Self::Widget> {
|
|
||||||
// self.add(state).handles()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// pub struct WidgetTag;
|
|
||||||
// impl<State: HasUi, W: Widget> WidgetLike<State, WidgetTag> for W {
|
|
||||||
// type Widget = W;
|
|
||||||
// fn add(self, state: &mut State) -> WidgetHandle<W> {
|
|
||||||
// state.get_mut().add_widget(self)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// on(move |ctx| {
|
|
||||||
// ().add(ctx);
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
ActiveData, Event, EventCtx, EventFn, EventIdCtx, EventLike, IdLike, LayerId, Widget,
|
|
||||||
WidgetData, WidgetEventFn, WidgetId, WidgetRef,
|
|
||||||
util::{HashMap, TypeMap},
|
|
||||||
};
|
|
||||||
use std::{any::TypeId, rc::Rc};
|
|
||||||
|
|
||||||
pub struct EventManager<State> {
|
|
||||||
types: TypeMap<dyn EventManagerLike<State>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State> Default for EventManager<State> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
types: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: 'static> EventManager<State> {
|
|
||||||
pub fn get_type<E: EventLike>(&mut self) -> &mut TypeEventManager<State, E::Event> {
|
|
||||||
self.types.type_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn register<W: Widget + ?Sized, E: EventLike>(
|
|
||||||
&mut self,
|
|
||||||
id: WidgetRef<W>,
|
|
||||||
event: E,
|
|
||||||
f: impl for<'a> WidgetEventFn<State, <E::Event as Event>::Data<'a>, W>,
|
|
||||||
) {
|
|
||||||
self.get_type::<E>().register(id, event, f);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn type_key<E: EventLike>() -> TypeId {
|
|
||||||
TypeId::of::<TypeEventManager<State, E::Event>>()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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() {
|
|
||||||
m.remove(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw(&mut self, data: &WidgetData, active: &ActiveData) {
|
|
||||||
for t in &data.event_mgrs {
|
|
||||||
self.types.get_mut(t).unwrap().draw(active);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn undraw(&mut self, data: &WidgetData, active: &ActiveData) {
|
|
||||||
for t in &data.event_mgrs {
|
|
||||||
self.types.get_mut(t).unwrap().undraw(active);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait EventManagerLike<State> {
|
|
||||||
fn remove(&mut self, id: WidgetId);
|
|
||||||
fn draw(&mut self, data: &ActiveData);
|
|
||||||
fn undraw(&mut self, data: &ActiveData);
|
|
||||||
}
|
|
||||||
|
|
||||||
type EventData<State, E> = (E, Rc<dyn for<'a> EventFn<State, <E as Event>::Data<'a>>>);
|
|
||||||
pub struct TypeEventManager<State, E: Event> {
|
|
||||||
// TODO: reduce visiblity!!
|
|
||||||
pub active: HashMap<LayerId, HashMap<WidgetId, E::State>>,
|
|
||||||
map: HashMap<WidgetId, Vec<EventData<State, E>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State, E: Event> EventManagerLike<State> for TypeEventManager<State, E> {
|
|
||||||
fn remove(&mut self, id: WidgetId) {
|
|
||||||
self.map.remove(&id);
|
|
||||||
for layer in self.active.values_mut() {
|
|
||||||
layer.remove(&id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn draw(&mut self, data: &ActiveData) {
|
|
||||||
self.active
|
|
||||||
.entry(data.layer)
|
|
||||||
.or_default()
|
|
||||||
.entry(data.id)
|
|
||||||
.or_default();
|
|
||||||
}
|
|
||||||
fn undraw(&mut self, data: &ActiveData) {
|
|
||||||
if let Some(layer) = self.active.get_mut(&data.layer) {
|
|
||||||
layer.remove(&data.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State, E: Event> Default for TypeEventManager<State, E> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
active: Default::default(),
|
|
||||||
map: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: 'static, E: Event> TypeEventManager<State, E> {
|
|
||||||
fn register<W: Widget + ?Sized>(
|
|
||||||
&mut self,
|
|
||||||
widget: WidgetRef<W>,
|
|
||||||
event: impl EventLike<Event = E>,
|
|
||||||
f: impl for<'a> WidgetEventFn<State, E::Data<'a>, W>,
|
|
||||||
) {
|
|
||||||
let event = event.into_event();
|
|
||||||
self.map.entry(widget.id()).or_default().push((
|
|
||||||
event,
|
|
||||||
Rc::new(move |ctx| {
|
|
||||||
let mut test = EventIdCtx {
|
|
||||||
widget,
|
|
||||||
state: ctx.state,
|
|
||||||
data: ctx.data,
|
|
||||||
};
|
|
||||||
f(&mut test);
|
|
||||||
}),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run_fn<'a>(
|
|
||||||
&mut self,
|
|
||||||
id: impl IdLike,
|
|
||||||
) -> impl for<'b> FnOnce(EventCtx<'_, State, E::Data<'b>>) + 'a {
|
|
||||||
let fs = self.map.get(&id.id()).cloned().unwrap_or_default();
|
|
||||||
move |ctx| {
|
|
||||||
for (e, f) in fs {
|
|
||||||
if e.should_run(ctx.data) {
|
|
||||||
f(&mut EventCtx {
|
|
||||||
state: ctx.state,
|
|
||||||
data: ctx.data,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
mod ctx;
|
|
||||||
mod manager;
|
|
||||||
mod rsc;
|
|
||||||
|
|
||||||
pub use ctx::*;
|
|
||||||
pub use manager::*;
|
|
||||||
pub use rsc::*;
|
|
||||||
|
|
||||||
pub trait Event: Sized + 'static + Clone {
|
|
||||||
type Data<'a> = ();
|
|
||||||
type State: Default = ();
|
|
||||||
#[allow(unused_variables)]
|
|
||||||
fn should_run(&self, data: &mut Self::Data<'_>) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait EventLike {
|
|
||||||
type Event: Event;
|
|
||||||
fn into_event(self) -> Self::Event;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<E: Event> EventLike for E {
|
|
||||||
type Event = Self;
|
|
||||||
|
|
||||||
fn into_event(self) -> Self::Event {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait EventFn<State, Data>: Fn(&mut EventCtx<State, Data>) + 'static {}
|
|
||||||
impl<State, F: Fn(&mut EventCtx<State, Data>) + 'static, Data> EventFn<State, Data> for F {}
|
|
||||||
|
|
||||||
pub trait WidgetEventFn<State, Data, W: ?Sized>:
|
|
||||||
Fn(&mut EventIdCtx<State, Data, W>) + 'static
|
|
||||||
{
|
|
||||||
}
|
|
||||||
impl<State, F: Fn(&mut EventIdCtx<State, Data, W>) + 'static, Data, W: ?Sized>
|
|
||||||
WidgetEventFn<State, Data, W> for F
|
|
||||||
{
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
Event, EventCtx, EventLike, EventManager, HasUi, IdLike, Widget, WidgetEventFn, WidgetRef,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub trait HasState {
|
|
||||||
type State: HasUi;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait HasEvents: Sized + HasState + HasUi {
|
|
||||||
fn get(&self) -> &EventManager<Self::State>;
|
|
||||||
fn get_mut(&mut self) -> &mut EventManager<Self::State>;
|
|
||||||
fn events(&self) -> &EventManager<Self::State> {
|
|
||||||
HasEvents::get(self)
|
|
||||||
}
|
|
||||||
fn events_mut(&mut self) -> &mut EventManager<Self::State> {
|
|
||||||
HasEvents::get_mut(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn register_event<W: Widget + ?Sized, E: EventLike>(
|
|
||||||
&mut self,
|
|
||||||
id: WidgetRef<W>,
|
|
||||||
event: E,
|
|
||||||
f: impl for<'a> WidgetEventFn<Self::State, <E::Event as Event>::Data<'a>, W>,
|
|
||||||
) where
|
|
||||||
Self::State: 'static,
|
|
||||||
{
|
|
||||||
self.events_mut().register(id, event, f);
|
|
||||||
self.ui_mut()
|
|
||||||
.widgets
|
|
||||||
.data_mut(id)
|
|
||||||
.unwrap()
|
|
||||||
.event_mgrs
|
|
||||||
.insert(EventManager::<Self::State>::type_key::<E>());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait RunEvents: HasEvents + HasState<State = Self> + 'static {
|
|
||||||
fn run_event<E: EventLike>(
|
|
||||||
&mut self,
|
|
||||||
id: impl IdLike,
|
|
||||||
data: &mut <E::Event as Event>::Data<'_>,
|
|
||||||
) {
|
|
||||||
let f = self.events_mut().get_type::<E>().run_fn(id);
|
|
||||||
f(EventCtx { state: self, data })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<T: HasEvents + HasState<State = Self> + 'static> RunEvents for T {}
|
|
||||||
20
core/src/layout/attr.rs
Normal file
20
core/src/layout/attr.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
use crate::layout::{Ui, WidgetIdFn, WidgetLike, WidgetRef};
|
||||||
|
|
||||||
|
pub trait WidgetAttr<W: ?Sized> {
|
||||||
|
type Input;
|
||||||
|
fn run(ui: &mut Ui, id: WidgetRef<W>, input: Self::Input);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Attrable<W: ?Sized, Tag> {
|
||||||
|
fn attr<A: WidgetAttr<W>>(self, input: A::Input) -> impl WidgetIdFn<W>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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.weak(), input);
|
||||||
|
id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
209
core/src/layout/event.rs
Normal file
209
core/src/layout/event.rs
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
use crate::{
|
||||||
|
layout::{LayerId, UiId, Widget, WidgetId, WidgetInstance, WidgetRef},
|
||||||
|
util::{Handle, HashMap, RefGuardMut},
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
any::{Any, TypeId},
|
||||||
|
ops::DerefMut,
|
||||||
|
sync::{Arc, LazyLock, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub trait Async: Send + Sync + 'static {}
|
||||||
|
impl<T: Send + Sync + 'static> Async for T {}
|
||||||
|
|
||||||
|
pub trait Event: Sized + Async + Clone {
|
||||||
|
type Data<'a> = ();
|
||||||
|
type State: Sync + Send + Default = ();
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
fn should_run(&self, data: &mut Self::Data<'_>) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// THIS SHOULD NOT BE OVERWRITTEN; the default impl runs this event
|
||||||
|
fn run<Ctx: 'static, W>(id: WidgetRef<W>, data: &mut Self::Data<'_>, state: &mut Ctx) {
|
||||||
|
Events::<Self, Ctx>::run(id.id(), data, state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait EventAlias {
|
||||||
|
type Event: Event;
|
||||||
|
fn into_event(self) -> Self::Event;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E: Event> EventAlias for E {
|
||||||
|
type Event = Self;
|
||||||
|
|
||||||
|
fn into_event(self) -> Self::Event {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type EventData<E, Ctx> = (E, Arc<dyn for<'a> EventFn<Ctx, <E as Event>::Data<'a>>>);
|
||||||
|
pub struct Events<E: Event, Ctx> {
|
||||||
|
active: HashMap<UiId, HashMap<LayerId, HashMap<WidgetId, E::State>>>,
|
||||||
|
map: HashMap<WidgetId, Vec<EventData<E, Ctx>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static EVENT_TYPES: LazyLock<Mutex<HashMap<TypeId, Handle<dyn EventManager>>>> =
|
||||||
|
LazyLock::new(|| Mutex::new(HashMap::default()));
|
||||||
|
|
||||||
|
pub trait EventManager: Any + Send + Sync {
|
||||||
|
fn remove(&mut self, id: WidgetId) -> Box<dyn Any>;
|
||||||
|
fn draw(&mut self, ui: UiId, inst: &WidgetInstance);
|
||||||
|
fn undraw(&mut self, ui: UiId, inst: &WidgetInstance);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Handle<dyn EventManager> {
|
||||||
|
pub fn remove(&mut self, id: WidgetId) {
|
||||||
|
let mut s = self.get_mut();
|
||||||
|
// refer to s.remove documentation for why drop order
|
||||||
|
let contents = s.remove(id);
|
||||||
|
drop(s);
|
||||||
|
drop(contents);
|
||||||
|
}
|
||||||
|
pub fn draw(&mut self, ui: UiId, inst: &WidgetInstance) {
|
||||||
|
self.get_mut().draw(ui, inst);
|
||||||
|
}
|
||||||
|
pub fn undraw(&mut self, ui: UiId, inst: &WidgetInstance) {
|
||||||
|
self.get_mut().undraw(ui, inst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E: Event, Ctx: 'static> EventManager for Events<E, Ctx> {
|
||||||
|
/// so... there is a deadlock if this is called in WidgetData::drop
|
||||||
|
/// and some function in here owns another WidgetId
|
||||||
|
/// so for now you need to drop the lock on self, THEN drop the contents
|
||||||
|
/// which is implemented for Handle<dyn EventManager>
|
||||||
|
fn remove(&mut self, id: WidgetId) -> Box<dyn Any> {
|
||||||
|
let contents = self.map.remove(&id);
|
||||||
|
for ui in self.active.values_mut() {
|
||||||
|
for layer in ui.values_mut() {
|
||||||
|
layer.remove(&id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Box::new(contents)
|
||||||
|
}
|
||||||
|
fn draw(&mut self, ui: UiId, inst: &WidgetInstance) {
|
||||||
|
self.active
|
||||||
|
.entry(ui)
|
||||||
|
.or_default()
|
||||||
|
.entry(inst.layer)
|
||||||
|
.or_default()
|
||||||
|
.entry(inst.id)
|
||||||
|
.or_default();
|
||||||
|
}
|
||||||
|
fn undraw(&mut self, ui: UiId, inst: &WidgetInstance) {
|
||||||
|
// rust pls
|
||||||
|
(|| {
|
||||||
|
self.active
|
||||||
|
.get_mut(&ui)?
|
||||||
|
.get_mut(&inst.layer)?
|
||||||
|
.remove(&inst.id);
|
||||||
|
Some(())
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type UiActive<State> = HashMap<LayerId, HashMap<WidgetId, State>>;
|
||||||
|
|
||||||
|
impl<E: Event, Ctx: 'static> Events<E, Ctx> {
|
||||||
|
fn id() -> TypeId {
|
||||||
|
TypeId::of::<Self>()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
map: Default::default(),
|
||||||
|
active: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active(id: UiId) -> impl DerefMut<Target = UiActive<E::State>> {
|
||||||
|
RefGuardMut::map(Self::get(), |s| s.active.entry(id).or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn register_<W: Widget + ?Sized>(
|
||||||
|
id: WidgetRef<W>,
|
||||||
|
event: impl Into<E>,
|
||||||
|
f: impl for<'a> EventFn<Ctx, <E as Event>::Data<'a>>,
|
||||||
|
) {
|
||||||
|
let Some(mut data) = id.data_mut() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
data.event_managers.insert(Self::id());
|
||||||
|
Self::get()
|
||||||
|
.map
|
||||||
|
.entry(id.id())
|
||||||
|
.or_default()
|
||||||
|
.push((event.into(), Arc::new(f)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn register<W: Widget + ?Sized + 'static>(
|
||||||
|
id: WidgetRef<W>,
|
||||||
|
event: impl Into<E>,
|
||||||
|
f: impl for<'a> EventIdFn<Ctx, <E as Event>::Data<'a>, W>,
|
||||||
|
) {
|
||||||
|
Self::register_(id, event, move |ctx| {
|
||||||
|
f(EventIdCtx {
|
||||||
|
widget: id,
|
||||||
|
state: ctx.state,
|
||||||
|
data: ctx.data,
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(id: WidgetId, data: &mut E::Data<'_>, state: &mut Ctx) {
|
||||||
|
let s = Self::get();
|
||||||
|
if let Some(fs) = s.map.get(&id) {
|
||||||
|
let fs = fs.clone();
|
||||||
|
drop(s);
|
||||||
|
for (e, f) in fs {
|
||||||
|
if e.should_run(data) {
|
||||||
|
f(EventCtx { state, data })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_all(data: &mut E::Data<'_>, state: &mut Ctx) {
|
||||||
|
let s = Self::get();
|
||||||
|
// TODO: should probably document that added events won't run same frame
|
||||||
|
let mut map = s.map.clone();
|
||||||
|
drop(s);
|
||||||
|
for fs in map.values_mut() {
|
||||||
|
for (e, f) in fs {
|
||||||
|
if e.should_run(data) {
|
||||||
|
f(EventCtx { state, data })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// this some bull
|
||||||
|
fn get<'a>() -> RefGuardMut<'a, Self> {
|
||||||
|
let any = EVENT_TYPES
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.entry(Self::id())
|
||||||
|
.or_insert_with(|| Handle::from(Self::new()))
|
||||||
|
.clone();
|
||||||
|
unsafe { any.downcast() }.get_take_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventCtx<'a, Ctx, Data> {
|
||||||
|
pub state: &'a mut Ctx,
|
||||||
|
pub data: &'a mut Data,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventIdCtx<'a, Ctx, Data, W: ?Sized> {
|
||||||
|
pub widget: WidgetRef<W>,
|
||||||
|
pub state: &'a mut Ctx,
|
||||||
|
pub data: &'a mut Data,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait EventFn<Ctx, Data>: Fn(EventCtx<Ctx, Data>) + Async {}
|
||||||
|
impl<F: Fn(EventCtx<Ctx, Data>) + Async, Ctx, Data> EventFn<Ctx, Data> for F {}
|
||||||
|
|
||||||
|
pub trait EventIdFn<Ctx, Data, W: ?Sized>: Fn(EventIdCtx<Ctx, Data, W>) + Async {}
|
||||||
|
impl<F: Fn(EventIdCtx<Ctx, Data, W>) + Async, Ctx, Data, W: ?Sized> EventIdFn<Ctx, Data, W> for F {}
|
||||||
24
core/src/layout/mod.rs
Normal file
24
core/src/layout/mod.rs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
mod attr;
|
||||||
|
mod event;
|
||||||
|
mod module;
|
||||||
|
mod num;
|
||||||
|
mod orientation;
|
||||||
|
mod painter;
|
||||||
|
mod primitive;
|
||||||
|
mod ui;
|
||||||
|
mod view;
|
||||||
|
mod widget;
|
||||||
|
|
||||||
|
pub use attr::*;
|
||||||
|
pub use event::*;
|
||||||
|
pub use module::*;
|
||||||
|
pub use num::*;
|
||||||
|
pub use orientation::*;
|
||||||
|
pub use painter::*;
|
||||||
|
pub use primitive::*;
|
||||||
|
pub use ui::*;
|
||||||
|
pub use view::*;
|
||||||
|
pub use widget::*;
|
||||||
|
|
||||||
|
pub use crate::util::Vec2;
|
||||||
|
pub type UiColor = Color<u8>;
|
||||||
35
core/src/layout/module.rs
Normal file
35
core/src/layout/module.rs
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
use std::any::{Any, TypeId};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
layout::{WidgetId, WidgetInstance},
|
||||||
|
util::HashMap,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
pub trait UiModule: Any {
|
||||||
|
fn on_draw(&mut self, inst: &WidgetInstance) {}
|
||||||
|
fn on_undraw(&mut self, inst: &WidgetInstance) {}
|
||||||
|
fn on_remove(&mut self, id: &WidgetId) {}
|
||||||
|
fn on_move(&mut self, inst: &WidgetInstance) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Modules {
|
||||||
|
map: HashMap<TypeId, Box<dyn UiModule>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Modules {
|
||||||
|
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut (dyn UiModule + 'static)> {
|
||||||
|
self.map.values_mut().map(|m| m.as_mut())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mut<M: UiModule + Default>(&mut self) -> &mut M {
|
||||||
|
let rf = self
|
||||||
|
.map
|
||||||
|
.entry(TypeId::of::<M>())
|
||||||
|
.or_insert_with(|| Box::new(M::default()))
|
||||||
|
.as_mut();
|
||||||
|
let any: &mut dyn Any = &mut *rf;
|
||||||
|
any.downcast_mut().unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,19 +23,6 @@ impl const UiNum for i32 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn vec2(x: impl const UiNum, y: impl const UiNum) -> Vec2 {
|
|
||||||
Vec2::new(x.to_f32(), y.to_f32())
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: const UiNum + Copy> const From<T> for Vec2 {
|
|
||||||
fn from(v: T) -> Self {
|
|
||||||
Self {
|
|
||||||
x: v.to_f32(),
|
|
||||||
y: v.to_f32(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: const UiNum, U: const UiNum> const From<(T, U)> for Vec2
|
impl<T: const UiNum, U: const UiNum> const From<(T, U)> for Vec2
|
||||||
where
|
where
|
||||||
(T, U): const Destruct,
|
(T, U): const Destruct,
|
||||||
@@ -47,3 +34,16 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T: const UiNum + Copy> const From<T> for Vec2 {
|
||||||
|
fn from(v: T) -> Self {
|
||||||
|
Self {
|
||||||
|
x: v.to_f32(),
|
||||||
|
y: v.to_f32(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn vec2(x: impl const UiNum, y: impl const UiNum) -> Vec2 {
|
||||||
|
Vec2::new(x.to_f32(), y.to_f32())
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::vec2;
|
use crate::layout::vec2;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
@@ -6,6 +6,9 @@ pub enum Axis {
|
|||||||
Y,
|
Y,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub trait Axis_ {
|
||||||
|
}
|
||||||
|
|
||||||
impl std::ops::Not for Axis {
|
impl std::ops::Not for Axis {
|
||||||
type Output = Self;
|
type Output = Self;
|
||||||
|
|
||||||
@@ -68,48 +71,3 @@ impl Vec2 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const trait AxisT {
|
|
||||||
fn get() -> Axis;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct XAxis;
|
|
||||||
impl const AxisT for XAxis {
|
|
||||||
fn get() -> Axis {
|
|
||||||
Axis::X
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct YAxis;
|
|
||||||
impl const AxisT for YAxis {
|
|
||||||
fn get() -> Axis {
|
|
||||||
Axis::Y
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default)]
|
|
||||||
pub struct BothAxis<T> {
|
|
||||||
pub x: T,
|
|
||||||
pub y: T,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> BothAxis<T> {
|
|
||||||
pub const fn axis<A: const AxisT>(&mut self) -> &mut T {
|
|
||||||
match A::get() {
|
|
||||||
Axis::X => &mut self.x,
|
|
||||||
Axis::Y => &mut self.y,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn take_axis<A: const AxisT>(self) -> T {
|
|
||||||
match A::get() {
|
|
||||||
Axis::X => self.x,
|
|
||||||
Axis::Y => self.y,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn axis_dyn(&mut self, axis: Axis) -> &mut T {
|
|
||||||
match axis {
|
|
||||||
Axis::X => &mut self.x,
|
|
||||||
Axis::Y => &mut self.y,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::{UiNum, util::impl_op};
|
use crate::{layout::UiNum, util::impl_op};
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Copy, PartialEq)]
|
#[derive(Debug, Default, Clone, Copy, PartialEq)]
|
||||||
pub struct Size {
|
pub struct Size {
|
||||||
@@ -3,8 +3,7 @@ mod axis;
|
|||||||
mod len;
|
mod len;
|
||||||
mod pos;
|
mod pos;
|
||||||
|
|
||||||
use crate::util::Vec2;
|
use super::Vec2;
|
||||||
|
|
||||||
pub use align::*;
|
pub use align::*;
|
||||||
pub use axis::*;
|
pub use axis::*;
|
||||||
pub use len::*;
|
pub use len::*;
|
||||||
@@ -2,7 +2,7 @@ use std::{fmt::Display, hash::Hash, marker::Destruct};
|
|||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::{
|
use crate::{
|
||||||
UiNum,
|
layout::UiNum,
|
||||||
util::{LerpUtil, impl_op},
|
util::{LerpUtil, impl_op},
|
||||||
};
|
};
|
||||||
|
|
||||||
617
core/src/layout/painter.rs
Normal file
617
core/src/layout/painter.rs
Normal file
@@ -0,0 +1,617 @@
|
|||||||
|
use std::{marker::Unsize, sync::mpsc::Sender};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
layout::{
|
||||||
|
Axis, LayerId, Len, PrimitiveLayers, RenderedText, Size, TextAttrs, TextBuffer, TextData,
|
||||||
|
TextureHandle, Textures, UiId, UiRegion, UiVec2, Vec2, Widget, WidgetHandle, WidgetId,
|
||||||
|
WidgetUpdate,
|
||||||
|
},
|
||||||
|
render::{Mask, MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst},
|
||||||
|
util::{HashMap, HashSet, RefMap, TrackedArena},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// makes your surfaces look pretty
|
||||||
|
pub struct Painter<'a, 'c> {
|
||||||
|
ctx: &'a mut PainterCtx<'c>,
|
||||||
|
widget: WidgetHandle,
|
||||||
|
id: WidgetId,
|
||||||
|
region: UiRegion,
|
||||||
|
mask: MaskIdx,
|
||||||
|
textures: Vec<TextureHandle>,
|
||||||
|
primitives: Vec<PrimitiveHandle>,
|
||||||
|
children: Vec<WidgetId>,
|
||||||
|
children_width: HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
children_height: HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
pub layer: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// context for a painter; lets you draw and redraw widgets
|
||||||
|
struct PainterCtx<'a> {
|
||||||
|
ui_id: UiId,
|
||||||
|
pub active: &'a mut HashMap<WidgetId, WidgetInstance>,
|
||||||
|
pub layers: &'a mut PrimitiveLayers,
|
||||||
|
pub textures: &'a mut Textures,
|
||||||
|
pub masks: &'a mut TrackedArena<Mask, u32>,
|
||||||
|
pub text: &'a mut TextData,
|
||||||
|
pub output_size: Vec2,
|
||||||
|
send: &'a Sender<WidgetUpdate>,
|
||||||
|
pub cache_width: HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
pub cache_height: HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
pub needs_redraw: HashSet<WidgetId>,
|
||||||
|
draw_started: HashSet<WidgetId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// stores information for children about the highest level parent that needed their size
|
||||||
|
/// so that they can redraw the parent if their size changes
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
pub struct ResizeRef {
|
||||||
|
x: Option<(WidgetId, (UiVec2, Len))>,
|
||||||
|
y: Option<(WidgetId, (UiVec2, Len))>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// important non rendering data for retained drawing
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct WidgetInstance {
|
||||||
|
pub id: WidgetId,
|
||||||
|
pub region: UiRegion,
|
||||||
|
pub parent: Option<WidgetId>,
|
||||||
|
pub textures: Vec<TextureHandle>,
|
||||||
|
pub primitives: Vec<PrimitiveHandle>,
|
||||||
|
pub children: Vec<WidgetId>,
|
||||||
|
pub resize: ResizeRef,
|
||||||
|
pub mask: MaskIdx,
|
||||||
|
pub layer: LayerId,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// data to be stored in Ui to create PainterCtxs easily
|
||||||
|
/// TODO: actually use this LMAO
|
||||||
|
pub struct PainterData {
|
||||||
|
ui_id: UiId,
|
||||||
|
pub active: HashMap<WidgetId, WidgetInstance>,
|
||||||
|
pub layers: PrimitiveLayers,
|
||||||
|
pub textures: Textures,
|
||||||
|
pub text: TextData,
|
||||||
|
pub output_size: Vec2,
|
||||||
|
pub px_dependent: HashSet<WidgetId>,
|
||||||
|
pub masks: TrackedArena<Mask, u32>,
|
||||||
|
send: Sender<WidgetUpdate>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PainterData {
|
||||||
|
pub fn new(ui_id: UiId, send: Sender<WidgetUpdate>) -> Self {
|
||||||
|
Self {
|
||||||
|
ui_id,
|
||||||
|
active: Default::default(),
|
||||||
|
layers: Default::default(),
|
||||||
|
textures: Default::default(),
|
||||||
|
text: Default::default(),
|
||||||
|
output_size: Default::default(),
|
||||||
|
px_dependent: Default::default(),
|
||||||
|
masks: Default::default(),
|
||||||
|
send,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> PainterCtx<'a> {
|
||||||
|
/// 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<W: Widget + ?Sized + Unsize<dyn Widget>>(&mut self, widget: &WidgetHandle<W>) {
|
||||||
|
let id = widget.id();
|
||||||
|
self.needs_redraw.remove(&id);
|
||||||
|
if self.draw_started.contains(&id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(active) = self.active.get(&id) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let mut resize = active.resize;
|
||||||
|
|
||||||
|
// set resize back after redrawing
|
||||||
|
let finish = |s: &mut Self, resize| {
|
||||||
|
if let Some(active) = s.active.get_mut(&id) {
|
||||||
|
// might need to get_or_insert here instead of just assuming
|
||||||
|
active.resize = resize;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// check if a parent depends on the desired size of this, if so then redraw it first
|
||||||
|
// TODO: this is stupid having 2 of these, don't ask me what the consequences are
|
||||||
|
let mut ret = false;
|
||||||
|
if let Some((rid, (outer, old_desired))) = &mut resize.x {
|
||||||
|
let new_desired = SizeCtx {
|
||||||
|
source: id,
|
||||||
|
cache_width: &mut self.cache_width,
|
||||||
|
cache_height: &mut self.cache_height,
|
||||||
|
text: self.text,
|
||||||
|
textures: self.textures,
|
||||||
|
outer: *outer,
|
||||||
|
output_size: self.output_size,
|
||||||
|
checked_width: &mut Default::default(),
|
||||||
|
checked_height: &mut Default::default(),
|
||||||
|
id,
|
||||||
|
}
|
||||||
|
.width(widget);
|
||||||
|
if new_desired != *old_desired
|
||||||
|
&& let Some(w) = rid.strong()
|
||||||
|
{
|
||||||
|
// unsure if I need to walk down the tree here
|
||||||
|
self.redraw(&w);
|
||||||
|
*old_desired = new_desired;
|
||||||
|
if self.draw_started.contains(&id) {
|
||||||
|
ret = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((rid, (outer, old_desired))) = &mut resize.y {
|
||||||
|
// NOTE: might need hack in Span here (or also do it properly here)
|
||||||
|
let new_desired = SizeCtx {
|
||||||
|
source: id,
|
||||||
|
cache_width: &mut self.cache_width,
|
||||||
|
cache_height: &mut self.cache_height,
|
||||||
|
text: self.text,
|
||||||
|
textures: self.textures,
|
||||||
|
outer: *outer,
|
||||||
|
output_size: self.output_size,
|
||||||
|
checked_width: &mut Default::default(),
|
||||||
|
checked_height: &mut Default::default(),
|
||||||
|
id,
|
||||||
|
}
|
||||||
|
.height(widget);
|
||||||
|
if new_desired != *old_desired
|
||||||
|
&& let Some(w) = rid.strong()
|
||||||
|
{
|
||||||
|
self.redraw(&w);
|
||||||
|
*old_desired = new_desired;
|
||||||
|
if self.draw_started.contains(&id) {
|
||||||
|
ret = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ret {
|
||||||
|
return finish(self, resize);
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(active) = self.remove(id, false) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
self.draw_inner(
|
||||||
|
active.layer,
|
||||||
|
widget,
|
||||||
|
active.region,
|
||||||
|
active.parent,
|
||||||
|
active.mask,
|
||||||
|
Some(active.children),
|
||||||
|
);
|
||||||
|
finish(self, resize);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_inner<W: Widget + ?Sized + Unsize<dyn Widget>>(
|
||||||
|
&mut self,
|
||||||
|
layer: usize,
|
||||||
|
widget: &WidgetHandle<W>,
|
||||||
|
region: UiRegion,
|
||||||
|
parent: Option<WidgetId>,
|
||||||
|
mask: MaskIdx,
|
||||||
|
old_children: Option<Vec<WidgetId>>,
|
||||||
|
) {
|
||||||
|
let id = widget.id();
|
||||||
|
widget.data_mut().send = Some(self.send.clone());
|
||||||
|
// 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 resize = ResizeRef::default();
|
||||||
|
if let Some(active) = self.active.get_mut(&id)
|
||||||
|
&& !self.needs_redraw.contains(&id)
|
||||||
|
{
|
||||||
|
// 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 {
|
||||||
|
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).unwrap();
|
||||||
|
old_children = active.children;
|
||||||
|
resize = active.resize;
|
||||||
|
}
|
||||||
|
|
||||||
|
// draw widget
|
||||||
|
self.draw_started.insert(id);
|
||||||
|
|
||||||
|
let mut painter = Painter {
|
||||||
|
region,
|
||||||
|
mask,
|
||||||
|
layer,
|
||||||
|
widget: widget.as_any(),
|
||||||
|
id,
|
||||||
|
textures: Vec::new(),
|
||||||
|
primitives: Vec::new(),
|
||||||
|
ctx: self,
|
||||||
|
children: Vec::new(),
|
||||||
|
children_width: Default::default(),
|
||||||
|
children_height: Default::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
widget.get_mut_quiet().draw(&mut painter);
|
||||||
|
|
||||||
|
let children_width = painter.children_width;
|
||||||
|
let children_height = painter.children_height;
|
||||||
|
|
||||||
|
// add to active
|
||||||
|
let instance = WidgetInstance {
|
||||||
|
id,
|
||||||
|
region,
|
||||||
|
parent,
|
||||||
|
textures: painter.textures,
|
||||||
|
primitives: painter.primitives,
|
||||||
|
children: painter.children,
|
||||||
|
resize,
|
||||||
|
mask: painter.mask,
|
||||||
|
layer,
|
||||||
|
};
|
||||||
|
// set resize for children who's size this widget depends on
|
||||||
|
for (cid, outer) in children_width {
|
||||||
|
if let Some(w) = self.active.get_mut(&cid)
|
||||||
|
&& w.resize.x.is_none()
|
||||||
|
{
|
||||||
|
w.resize.x = Some((id, outer))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (cid, outer) in children_height {
|
||||||
|
if let Some(w) = self.active.get_mut(&cid)
|
||||||
|
&& w.resize.y.is_none()
|
||||||
|
{
|
||||||
|
w.resize.y = Some((id, outer))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove old children that weren't kept
|
||||||
|
for c in &old_children {
|
||||||
|
if !instance.children.contains(c) {
|
||||||
|
self.remove_rec(*c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// run events
|
||||||
|
id.map_event_managers(|mut m| {
|
||||||
|
m.draw(self.ui_id, &instance);
|
||||||
|
});
|
||||||
|
self.active.insert(id, instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
// children will not be changed, so this technically should not be needed
|
||||||
|
// probably need unsafe
|
||||||
|
let children = active.children.clone();
|
||||||
|
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) -> Option<WidgetInstance> {
|
||||||
|
let mut inst = self.active.remove(&id);
|
||||||
|
if let Some(inst) = &mut inst {
|
||||||
|
for h in &inst.primitives {
|
||||||
|
let mask = self.layers.free(h);
|
||||||
|
if mask != MaskIdx::NONE {
|
||||||
|
self.masks.remove(mask);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inst.textures.clear();
|
||||||
|
self.textures.free();
|
||||||
|
if undraw {
|
||||||
|
id.map_event_managers(|mut m| {
|
||||||
|
m.undraw(self.ui_id, inst);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inst
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_rec(&mut self, id: WidgetId) -> Option<WidgetInstance> {
|
||||||
|
let inst = self.remove(id, true);
|
||||||
|
if let Some(inst) = &inst {
|
||||||
|
for c in &inst.children {
|
||||||
|
self.remove_rec(*c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inst
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PainterData {
|
||||||
|
fn ctx(&mut self, needs_redraw: HashSet<WidgetId>) -> PainterCtx<'_> {
|
||||||
|
PainterCtx {
|
||||||
|
ui_id: self.ui_id,
|
||||||
|
active: &mut self.active,
|
||||||
|
layers: &mut self.layers,
|
||||||
|
textures: &mut self.textures,
|
||||||
|
text: &mut self.text,
|
||||||
|
output_size: self.output_size,
|
||||||
|
masks: &mut self.masks,
|
||||||
|
send: &self.send,
|
||||||
|
cache_width: Default::default(),
|
||||||
|
cache_height: Default::default(),
|
||||||
|
draw_started: Default::default(),
|
||||||
|
needs_redraw,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw<W: Widget + ?Sized + Unsize<dyn Widget>>(&mut self, id: &WidgetHandle<W>) {
|
||||||
|
let mut ctx = self.ctx(Default::default());
|
||||||
|
ctx.draw_started.clear();
|
||||||
|
ctx.layers.clear();
|
||||||
|
ctx.draw_inner(0, id, UiRegion::FULL, None, MaskIdx::NONE, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redraw(&mut self, ids: HashSet<WidgetId>) {
|
||||||
|
let mut ctx = self.ctx(ids);
|
||||||
|
while let Some(&id) = ctx.needs_redraw.iter().next() {
|
||||||
|
if let Some(w) = id.strong() {
|
||||||
|
ctx.redraw(&w);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'c> Painter<'a, 'c> {
|
||||||
|
fn primitive_at<P: Primitive>(&mut self, primitive: P, region: UiRegion) {
|
||||||
|
let h = self.ctx.layers.write(
|
||||||
|
self.layer,
|
||||||
|
PrimitiveInst {
|
||||||
|
id: self.id(),
|
||||||
|
primitive,
|
||||||
|
region,
|
||||||
|
mask_idx: self.mask,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if self.mask != MaskIdx::NONE {
|
||||||
|
// TODO: I have no clue if this works at all :joy:
|
||||||
|
self.ctx.masks.push_ref(self.mask);
|
||||||
|
}
|
||||||
|
self.primitives.push(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a primitive to be rendered
|
||||||
|
pub fn primitive<P: Primitive>(&mut self, primitive: P) {
|
||||||
|
self.primitive_at(primitive, self.region)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn primitive_within<P: Primitive>(&mut self, primitive: P, region: UiRegion) {
|
||||||
|
self.primitive_at(primitive, region.within(&self.region));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_mask(&mut self, region: UiRegion) {
|
||||||
|
assert!(self.mask == MaskIdx::NONE);
|
||||||
|
self.mask = self.ctx.masks.push(Mask { region });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draws a widget within this widget's region.
|
||||||
|
pub fn widget<W: Widget + ?Sized + Unsize<dyn Widget>>(&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: Widget + ?Sized + Unsize<dyn Widget>>(
|
||||||
|
&mut self,
|
||||||
|
id: &WidgetHandle<W>,
|
||||||
|
region: UiRegion,
|
||||||
|
) {
|
||||||
|
self.widget_at(id, region.within(&self.region));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn widget_at<W: Widget + ?Sized + Unsize<dyn Widget>>(
|
||||||
|
&mut self,
|
||||||
|
id: &WidgetHandle<W>,
|
||||||
|
region: UiRegion,
|
||||||
|
) {
|
||||||
|
self.children.push(id.id());
|
||||||
|
self.ctx
|
||||||
|
.draw_inner(self.layer, id, region, Some(self.id()), self.mask, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn texture_within(&mut self, handle: &TextureHandle, region: UiRegion) {
|
||||||
|
self.textures.push(handle.clone());
|
||||||
|
self.primitive_at(handle.primitive(), region.within(&self.region));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn texture(&mut self, handle: &TextureHandle) {
|
||||||
|
self.textures.push(handle.clone());
|
||||||
|
self.primitive(handle.primitive());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn texture_at(&mut self, handle: &TextureHandle, region: UiRegion) {
|
||||||
|
self.textures.push(handle.clone());
|
||||||
|
self.primitive_at(handle.primitive(), region);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// returns (handle, offset from top left)
|
||||||
|
pub fn render_text(&mut self, buffer: &mut TextBuffer, attrs: &TextAttrs) -> RenderedText {
|
||||||
|
self.ctx
|
||||||
|
.text
|
||||||
|
.get_mut()
|
||||||
|
.draw(buffer, attrs, self.ctx.textures)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn region(&self) -> UiRegion {
|
||||||
|
self.region
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn size<W: Widget + ?Sized>(&mut self, id: &WidgetHandle<W>) -> Size {
|
||||||
|
self.size_ctx().size(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len_axis<W: Widget + ?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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn size_ctx(&mut self) -> SizeCtx<'_> {
|
||||||
|
SizeCtx {
|
||||||
|
source: self.id(),
|
||||||
|
id: self.id(),
|
||||||
|
text: self.ctx.text,
|
||||||
|
textures: self.ctx.textures,
|
||||||
|
output_size: self.ctx.output_size,
|
||||||
|
checked_width: &mut self.children_width,
|
||||||
|
checked_height: &mut self.children_height,
|
||||||
|
cache_width: &mut self.ctx.cache_width,
|
||||||
|
cache_height: &mut self.ctx.cache_height,
|
||||||
|
outer: self.region.size(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn output_size(&self) -> Vec2 {
|
||||||
|
self.ctx.output_size
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn px_size(&mut self) -> Vec2 {
|
||||||
|
self.region.size().to_abs(self.ctx.output_size)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn text_data(&mut self) -> &mut TextData {
|
||||||
|
self.ctx.text
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn child_layer(&mut self) {
|
||||||
|
self.layer = self.ctx.layers.child(self.layer);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next_layer(&mut self) {
|
||||||
|
self.layer = self.ctx.layers.next(self.layer);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn label(&self) -> RefMap<'_, String> {
|
||||||
|
self.widget.get_label()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn id(&self) -> WidgetId {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SizeCtx<'a> {
|
||||||
|
pub text: &'a mut TextData,
|
||||||
|
pub textures: &'a mut Textures,
|
||||||
|
source: WidgetId,
|
||||||
|
cache_width: &'a mut HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
cache_height: &'a mut HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
checked_width: &'a mut HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
checked_height: &'a mut HashMap<WidgetId, (UiVec2, Len)>,
|
||||||
|
/// TODO: should this be pub? rn used for sized
|
||||||
|
pub outer: UiVec2,
|
||||||
|
output_size: Vec2,
|
||||||
|
id: WidgetId,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SizeCtx<'_> {
|
||||||
|
pub fn id(&self) -> &WidgetId {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn source(&self) -> &WidgetId {
|
||||||
|
&self.source
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn width<W: Widget + ?Sized>(&mut self, widget: &WidgetHandle<W>) -> Len {
|
||||||
|
// first check cache
|
||||||
|
// TODO: is this needed? broken rn bc does not store children during upper size check,
|
||||||
|
// so if something actually using check_* hits cache it fails to add them
|
||||||
|
// if let Some(&(outer, len)) = self.cache_width.get(&id)
|
||||||
|
// && outer == self.outer
|
||||||
|
// {
|
||||||
|
// self.checked_width.insert(id, (self.outer, len));
|
||||||
|
// return len;
|
||||||
|
// }
|
||||||
|
// store self vars that need to be maintained
|
||||||
|
let id = widget.id();
|
||||||
|
let self_outer = self.outer;
|
||||||
|
let self_id = self.id;
|
||||||
|
// get size of input id
|
||||||
|
self.id = id;
|
||||||
|
let len = widget.get_mut_quiet().desired_width(self);
|
||||||
|
// restore vars & update cache + checked
|
||||||
|
self.outer = self_outer;
|
||||||
|
self.id = self_id;
|
||||||
|
self.cache_width.insert(id, (self.outer, len));
|
||||||
|
self.checked_width.insert(id, (self.outer, len));
|
||||||
|
len
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: should be refactored to share code w width_inner
|
||||||
|
pub fn height<W: Widget + ?Sized>(&mut self, widget: &WidgetHandle<W>) -> Len {
|
||||||
|
// if let Some(&(outer, len)) = self.cache_height.get(&id)
|
||||||
|
// && outer == self.outer
|
||||||
|
// {
|
||||||
|
// self.checked_height.insert(id, (self.outer, len));
|
||||||
|
// return len;
|
||||||
|
// }
|
||||||
|
let id = widget.id();
|
||||||
|
let self_outer = self.outer;
|
||||||
|
let self_id = self.id;
|
||||||
|
self.id = id;
|
||||||
|
let len = widget.get_mut_quiet().desired_height(self);
|
||||||
|
self.outer = self_outer;
|
||||||
|
self.id = self_id;
|
||||||
|
self.cache_height.insert(id, (self.outer, len));
|
||||||
|
self.checked_height.insert(id, (self.outer, len));
|
||||||
|
len
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len_axis<W: Widget + ?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: Widget + ?Sized>(&mut self, id: &WidgetHandle<W>) -> Size {
|
||||||
|
Size {
|
||||||
|
x: self.width(id),
|
||||||
|
y: self.height(id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn px_size(&mut self) -> Vec2 {
|
||||||
|
self.outer.to_abs(self.output_size)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn output_size(&mut self) -> Vec2 {
|
||||||
|
self.output_size
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_text(&mut self, buffer: &mut TextBuffer, attrs: &TextAttrs) -> RenderedText {
|
||||||
|
self.text.get_mut().draw(buffer, attrs, self.textures)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
|
#![allow(clippy::multiple_bound_locations)]
|
||||||
|
|
||||||
use std::marker::Destruct;
|
use std::marker::Destruct;
|
||||||
|
|
||||||
/// stored in linear for sane manipulation
|
/// stored in linear for sane manipulation
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
#[derive(Clone, Copy, Hash, PartialEq, Eq, bytemuck::Zeroable, Debug)]
|
#[derive(Clone, Copy, Hash, PartialEq, Eq, bytemuck::Zeroable, Debug)]
|
||||||
pub struct Color<T> {
|
pub struct Color<T: ColorNum> {
|
||||||
pub r: T,
|
pub r: T,
|
||||||
pub g: T,
|
pub g: T,
|
||||||
pub b: T,
|
pub b: T,
|
||||||
@@ -1,9 +1,6 @@
|
|||||||
use std::ops::{Index, IndexMut};
|
use std::ops::{Index, IndexMut};
|
||||||
|
|
||||||
use crate::{
|
use crate::render::{MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst, Primitives};
|
||||||
render::{MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst, Primitives},
|
|
||||||
util::to_mut,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub type LayerId = usize;
|
pub type LayerId = usize;
|
||||||
|
|
||||||
@@ -54,13 +51,13 @@ impl<T: Default> Layers<T> {
|
|||||||
self.vec.push(LayerNode::head());
|
self.vec.push(LayerNode::head());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn push(&mut self, node: LayerNode<T>) -> LayerId {
|
fn push(&mut self, node: LayerNode<T>) -> usize {
|
||||||
let i = self.vec.len();
|
let i = self.vec.len();
|
||||||
self.vec.push(node);
|
self.vec.push(node);
|
||||||
i
|
i
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn next(&mut self, i: LayerId) -> LayerId {
|
pub fn next(&mut self, i: usize) -> usize {
|
||||||
if let Ptr::Next(i) = self.vec[i].next {
|
if let Ptr::Next(i) = self.vec[i].next {
|
||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
@@ -80,7 +77,7 @@ impl<T: Default> Layers<T> {
|
|||||||
i_new
|
i_new
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn child(&mut self, i: LayerId) -> LayerId {
|
pub fn child(&mut self, i: usize) -> usize {
|
||||||
if let Some(c) = self.vec[i].child {
|
if let Some(c) = self.vec[i].child {
|
||||||
return c.head;
|
return c.head;
|
||||||
}
|
}
|
||||||
@@ -105,11 +102,11 @@ impl<T: Default> Layers<T> {
|
|||||||
self.vec.iter_mut().map(|n| &mut n.data).enumerate()
|
self.vec.iter_mut().map(|n| &mut n.data).enumerate()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn iter(&self) -> impl Iterator<Item = (LayerId, &T)> {
|
pub fn iter(&self) -> impl Iterator<Item = (usize, &T)> {
|
||||||
self.indices().map(|i| (i, &self.vec[i].data))
|
self.indices().map(|i| (i, &self.vec[i].data))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn iter_depth(&self) -> impl Iterator<Item = ((LayerId, usize), &T)> {
|
pub fn iter_depth(&self) -> impl Iterator<Item = ((usize, usize), &T)> {
|
||||||
self.indices()
|
self.indices()
|
||||||
.map(|i| ((i, self.vec[i].depth), &self.vec[i].data))
|
.map(|i| ((i, self.vec[i].depth), &self.vec[i].data))
|
||||||
}
|
}
|
||||||
@@ -120,11 +117,7 @@ impl<T: Default> Layers<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PrimitiveLayers {
|
impl PrimitiveLayers {
|
||||||
pub fn write<P: Primitive>(
|
pub fn write<P: Primitive>(&mut self, layer: usize, info: PrimitiveInst<P>) -> PrimitiveHandle {
|
||||||
&mut self,
|
|
||||||
layer: LayerId,
|
|
||||||
info: PrimitiveInst<P>,
|
|
||||||
) -> PrimitiveHandle {
|
|
||||||
self[layer].write(layer, info)
|
self[layer].write(layer, info)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,16 +132,16 @@ impl<T: Default> Default for Layers<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Index<LayerId> for Layers<T> {
|
impl<T> Index<usize> for Layers<T> {
|
||||||
type Output = T;
|
type Output = T;
|
||||||
|
|
||||||
fn index(&self, index: LayerId) -> &Self::Output {
|
fn index(&self, index: usize) -> &Self::Output {
|
||||||
&self.vec[index].data
|
&self.vec[index].data
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> IndexMut<LayerId> for Layers<T> {
|
impl<T> IndexMut<usize> for Layers<T> {
|
||||||
fn index_mut(&mut self, index: LayerId) -> &mut Self::Output {
|
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
|
||||||
&mut self.vec[index].data
|
&mut self.vec[index].data
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,7 +172,8 @@ impl<'a, T> Iterator for LayerIteratorMut<'a, T> {
|
|||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
let i = self.inner.next()?;
|
let i = self.inner.next()?;
|
||||||
// SAFETY: requires index iterator to work properly
|
// SAFETY: requires index iterator to work properly
|
||||||
let layer = unsafe { to_mut(&self.inner.vec[i].data) };
|
#[allow(mutable_transmutes)]
|
||||||
|
let layer = unsafe { std::mem::transmute::<&T, &mut T>(&self.inner.vec[i].data) };
|
||||||
Some((i, layer))
|
Some((i, layer))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,7 +182,8 @@ impl<'a, T> DoubleEndedIterator for LayerIteratorMut<'a, T> {
|
|||||||
fn next_back(&mut self) -> Option<Self::Item> {
|
fn next_back(&mut self) -> Option<Self::Item> {
|
||||||
let i = self.inner.next_back()?;
|
let i = self.inner.next_back()?;
|
||||||
// SAFETY: requires index iterator to work properly
|
// SAFETY: requires index iterator to work properly
|
||||||
let layer = unsafe { to_mut(&self.inner.vec[i].data) };
|
#[allow(mutable_transmutes)]
|
||||||
|
let layer = unsafe { std::mem::transmute::<&T, &mut T>(&self.inner.vec[i].data) };
|
||||||
Some((i, layer))
|
Some((i, layer))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
46
core/src/layout/primitive/mask.rs
Normal file
46
core/src/layout/primitive/mask.rs
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
//! tree structure for masking
|
||||||
|
|
||||||
|
use crate::layout::UiRegion;
|
||||||
|
|
||||||
|
pub struct Masks {
|
||||||
|
data: Vec<MaskNode>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct MaskPtr(u32);
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct MaskNode {
|
||||||
|
/// TODO: this is just a rect for now,
|
||||||
|
/// but would like to support arbitrary masks
|
||||||
|
/// at some point; custom shader
|
||||||
|
/// would probably handle that case
|
||||||
|
/// bc you'd need to render to a special target
|
||||||
|
/// anyways
|
||||||
|
region: UiRegion,
|
||||||
|
prev: MaskPtr,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MaskPtr {
|
||||||
|
const NONE: Self = Self(u32::MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Masks {
|
||||||
|
pub fn push(&mut self, parent: MaskPtr, region: UiRegion) -> MaskPtr {
|
||||||
|
match parent.0 {
|
||||||
|
_ => {
|
||||||
|
}
|
||||||
|
u32::MAX => {
|
||||||
|
let i = self.data.len();
|
||||||
|
self.data.push(MaskNode {
|
||||||
|
region,
|
||||||
|
prev: parent,
|
||||||
|
});
|
||||||
|
MaskPtr(i as u32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pop(&mut self, i: usize) {}
|
||||||
|
}
|
||||||
@@ -1,23 +1,29 @@
|
|||||||
use crate::{Align, RegionAlign, TextureHandle, Textures, UiColor, util::Vec2};
|
use std::simd::{Simd, num::SimdUint};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
layout::{Align, RegionAlign, TextureHandle, Textures, UiColor, Vec2},
|
||||||
|
util::Handle,
|
||||||
|
};
|
||||||
use cosmic_text::{
|
use cosmic_text::{
|
||||||
Attrs, AttrsList, Buffer, CacheKey, Color, Family, FontSystem, Metrics, Placement, SwashCache,
|
Attrs, AttrsList, Buffer, CacheKey, Color, Family, FontSystem, Metrics, Placement, SwashCache,
|
||||||
SwashContent,
|
SwashContent,
|
||||||
};
|
};
|
||||||
use image::{GenericImageView, RgbaImage};
|
use image::{GenericImageView, RgbaImage};
|
||||||
use std::simd::{Simd, num::SimdUint};
|
|
||||||
|
|
||||||
/// TODO: properly wrap this
|
/// TODO: properly wrap this
|
||||||
pub mod text_lib {
|
pub mod text_lib {
|
||||||
pub use cosmic_text::*;
|
pub use cosmic_text::*;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct TextData {
|
pub type TextData = Handle<TextDataInner>;
|
||||||
|
|
||||||
|
pub struct TextDataInner {
|
||||||
pub font_system: FontSystem,
|
pub font_system: FontSystem,
|
||||||
pub swash_cache: SwashCache,
|
pub swash_cache: SwashCache,
|
||||||
glyph_cache: Vec<(Placement, CacheKey, Color)>,
|
glyph_cache: Vec<(Placement, CacheKey, Color)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for TextData {
|
impl Default for TextDataInner {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
font_system: FontSystem::new(),
|
font_system: FontSystem::new(),
|
||||||
@@ -58,7 +64,7 @@ pub type TextBuffer = Buffer;
|
|||||||
|
|
||||||
impl Default for TextAttrs {
|
impl Default for TextAttrs {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
let size = 16.0;
|
let size = 14.0;
|
||||||
Self {
|
Self {
|
||||||
color: UiColor::WHITE,
|
color: UiColor::WHITE,
|
||||||
font_size: size,
|
font_size: size,
|
||||||
@@ -72,7 +78,7 @@ impl Default for TextAttrs {
|
|||||||
|
|
||||||
pub const LINE_HEIGHT_MULT: f32 = 1.1;
|
pub const LINE_HEIGHT_MULT: f32 = 1.1;
|
||||||
|
|
||||||
impl TextData {
|
impl TextDataInner {
|
||||||
pub fn draw(
|
pub fn draw(
|
||||||
&mut self,
|
&mut self,
|
||||||
buffer: &mut TextBuffer,
|
buffer: &mut TextBuffer,
|
||||||
@@ -1,13 +1,12 @@
|
|||||||
use crate::{
|
|
||||||
render::TexturePrimitive,
|
|
||||||
util::{RefCounter, Vec2},
|
|
||||||
};
|
|
||||||
use image::{DynamicImage, GenericImageView};
|
|
||||||
use std::{
|
use std::{
|
||||||
ops::Index,
|
ops::Index,
|
||||||
sync::mpsc::{Receiver, Sender, channel},
|
sync::mpsc::{Receiver, Sender, channel},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use image::{DynamicImage, GenericImageView};
|
||||||
|
|
||||||
|
use crate::{layout::Vec2, render::TexturePrimitive, util::RefCounter};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct TextureHandle {
|
pub struct TextureHandle {
|
||||||
inner: TexturePrimitive,
|
inner: TexturePrimitive,
|
||||||
159
core/src/layout/ui.rs
Normal file
159
core/src/layout/ui.rs
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
use image::DynamicImage;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
layout::{
|
||||||
|
IdLike, PainterData, PixelRegion, TextureHandle, Vec2, WidgetHandle, WidgetId,
|
||||||
|
WidgetInstance, WidgetLike, WidgetUpdate,
|
||||||
|
},
|
||||||
|
util::{HashMap, HashSet, Id, StaticIdTracker},
|
||||||
|
};
|
||||||
|
use std::sync::mpsc::{Receiver, channel};
|
||||||
|
|
||||||
|
static ID_TRACKER: StaticIdTracker = StaticIdTracker::new();
|
||||||
|
pub type UiId = Id;
|
||||||
|
|
||||||
|
pub struct Ui {
|
||||||
|
id: UiId,
|
||||||
|
pub(crate) data: PainterData,
|
||||||
|
root: Option<WidgetHandle>,
|
||||||
|
updates: HashSet<WidgetId>,
|
||||||
|
recv: Receiver<WidgetUpdate>,
|
||||||
|
full_redraw: bool,
|
||||||
|
resized: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ui {
|
||||||
|
pub fn id(&self) -> UiId {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
pub fn set_root<Tag>(&mut self, w: impl WidgetLike<Tag>) {
|
||||||
|
self.root = Some(w.add(self));
|
||||||
|
self.full_redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_texture(&mut self, image: DynamicImage) -> TextureHandle {
|
||||||
|
self.data.textures.add(image)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resize(&mut self, size: impl Into<Vec2>) {
|
||||||
|
self.data.output_size = size.into();
|
||||||
|
self.resized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn redraw_all(&mut self) {
|
||||||
|
for (id, inst) in self.data.active.drain() {
|
||||||
|
id.map_event_managers(|mut m| {
|
||||||
|
m.undraw(self.id, &inst);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// free before bc nothing should exist
|
||||||
|
self.free();
|
||||||
|
if let Some(root) = &self.root {
|
||||||
|
self.data.draw(root);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&mut self) -> bool {
|
||||||
|
for id in self.recv.try_iter() {
|
||||||
|
self.updates.insert(id);
|
||||||
|
}
|
||||||
|
if self.full_redraw {
|
||||||
|
self.redraw_all();
|
||||||
|
self.full_redraw = false;
|
||||||
|
true
|
||||||
|
} else if self.resized {
|
||||||
|
self.resized = false;
|
||||||
|
self.redraw_all();
|
||||||
|
true
|
||||||
|
} else if !self.updates.is_empty() {
|
||||||
|
self.redraw_updates();
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn redraw_updates(&mut self) {
|
||||||
|
self.data.redraw(std::mem::take(&mut self.updates));
|
||||||
|
self.free();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// free any resources that don't have references anymore
|
||||||
|
fn free(&mut self) {
|
||||||
|
self.data.textures.free();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn needs_redraw(&self) -> bool {
|
||||||
|
self.full_redraw || !self.updates.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active_widgets(&self) -> usize {
|
||||||
|
self.data.active.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active(&self) -> &HashMap<WidgetId, WidgetInstance> {
|
||||||
|
&self.data.active
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn debug_layers(&self) {
|
||||||
|
for ((idx, depth), primitives) in self.data.layers.iter_depth() {
|
||||||
|
let indent = " ".repeat(depth * 2);
|
||||||
|
let len = primitives.instances().len();
|
||||||
|
print!("{indent}{idx}: {len} primitives");
|
||||||
|
if len >= 1 {
|
||||||
|
print!(" ({})", primitives.instances()[0].binding);
|
||||||
|
}
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn window_region<W>(&self, id: &impl IdLike<W>) -> Option<PixelRegion> {
|
||||||
|
let region = self.data.active.get(&id.id())?.region;
|
||||||
|
Some(region.to_px(self.data.output_size))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn debug(&self, label: &str) -> impl Iterator<Item = &WidgetInstance> {
|
||||||
|
self.data.active.iter().filter_map(move |(id, inst)| {
|
||||||
|
let widget = id.strong().unwrap();
|
||||||
|
if widget.get_label().as_str() == label {
|
||||||
|
Some(inst)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn data(&self) -> &PainterData {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn data_mut(&mut self) -> &mut PainterData {
|
||||||
|
&mut self.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Ui {
|
||||||
|
fn default() -> Self {
|
||||||
|
let (send, recv) = channel();
|
||||||
|
let id = ID_TRACKER.next();
|
||||||
|
Self {
|
||||||
|
id,
|
||||||
|
data: PainterData::new(id, send),
|
||||||
|
root: Default::default(),
|
||||||
|
updates: Default::default(),
|
||||||
|
full_redraw: false,
|
||||||
|
recv,
|
||||||
|
resized: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Ui {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
ID_TRACKER.free(self.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
17
core/src/layout/view.rs
Normal file
17
core/src/layout/view.rs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
use crate::layout::{Widget, WidgetHandle, WidgetLike};
|
||||||
|
use std::marker::Unsize;
|
||||||
|
|
||||||
|
pub trait WidgetView {
|
||||||
|
type Widget: Widget + ?Sized + Unsize<dyn Widget> = dyn Widget;
|
||||||
|
fn view(self) -> WidgetHandle<Self::Widget>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ViewTag;
|
||||||
|
|
||||||
|
impl<WV: WidgetView> WidgetLike<ViewTag> for WV {
|
||||||
|
type Widget = WV::Widget;
|
||||||
|
|
||||||
|
fn add(self, _ui: &mut super::Ui) -> WidgetHandle<Self::Widget> {
|
||||||
|
self.view()
|
||||||
|
}
|
||||||
|
}
|
||||||
31
core/src/layout/widget/data.rs
Normal file
31
core/src/layout/widget/data.rs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
use std::{any::TypeId, sync::mpsc::Sender};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
layout::{EVENT_TYPES, EventManager, WIDGETS, WidgetId, WidgetUpdate},
|
||||||
|
util::{Handle, HashSet},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct WidgetData<W: ?Sized> {
|
||||||
|
pub id: WidgetId,
|
||||||
|
pub send: Option<Sender<WidgetUpdate>>,
|
||||||
|
pub label: String,
|
||||||
|
pub event_managers: HashSet<TypeId>,
|
||||||
|
pub widget: W,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: ?Sized> WidgetData<W> {
|
||||||
|
pub(crate) fn event_managers(&self) -> impl Iterator<Item = Handle<dyn EventManager>> {
|
||||||
|
self.event_managers
|
||||||
|
.iter()
|
||||||
|
.map(|id| EVENT_TYPES.lock().unwrap().get_mut(id).unwrap().clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: ?Sized> Drop for WidgetData<W> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
WIDGETS.remove(self.id);
|
||||||
|
for mut m in self.event_managers() {
|
||||||
|
m.remove(self.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
244
core/src/layout/widget/handle.rs
Normal file
244
core/src/layout/widget/handle.rs
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
use std::{marker::Unsize, mem::MaybeUninit, ops::CoerceUnsized};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
layout::{EventManager, IdFnTag, IdTag, Ui, WIDGETS, Widget, WidgetData, WidgetLike},
|
||||||
|
util::{
|
||||||
|
Handle, MappedRefGuard, MappedRefGuardMut, Ref, RefGuard, RefGuardMut, RefMap, RefMapMut,
|
||||||
|
RefMut, WeakHandle,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) type SlotTy = u32;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct WidgetId {
|
||||||
|
pub(super) i: SlotTy,
|
||||||
|
pub(super) genr: SlotTy,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A strong handle to a widget. Cannot be cloned, only one may exist
|
||||||
|
/// Use .weak() to obtain weak references to this
|
||||||
|
pub struct WidgetHandle<W: ?Sized = dyn Widget>(WidgetId, Handle<WidgetData<W>>);
|
||||||
|
/// A weak handle to a widget. Implements Copy so you can easily pass into closures
|
||||||
|
pub struct WidgetRef<W: ?Sized = dyn Widget>(WidgetId, *const W);
|
||||||
|
|
||||||
|
pub type WidgetUpdate = WidgetId;
|
||||||
|
|
||||||
|
impl<W: Widget> WidgetHandle<W> {
|
||||||
|
pub(super) fn new(id: WidgetId, widget: W) -> Self {
|
||||||
|
let mut label = std::any::type_name::<W>().to_string();
|
||||||
|
if let (Some(first), Some(last)) = (label.find(":"), label.rfind(":")) {
|
||||||
|
label = label.split_at(first).0.to_string() + "::" + label.split_at(last + 1).1;
|
||||||
|
}
|
||||||
|
Self(
|
||||||
|
id,
|
||||||
|
WidgetData {
|
||||||
|
id,
|
||||||
|
widget,
|
||||||
|
send: None,
|
||||||
|
label,
|
||||||
|
event_managers: Default::default(),
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Widget + ?Sized + Unsize<dyn Widget>> WidgetHandle<W> {
|
||||||
|
pub(super) fn weak_inner(&self) -> WeakHandle<WidgetData<W>> {
|
||||||
|
self.1.weak()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn any(self) -> WidgetHandle<dyn Widget> {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DO NOT CALL OTHER THAN TEMP IN PAINTER
|
||||||
|
pub(crate) fn as_any(&self) -> WidgetHandle<dyn Widget> {
|
||||||
|
WidgetHandle(self.0, self.1.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: ?Sized> WidgetHandle<W> {
|
||||||
|
pub fn id(&self) -> WidgetId {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self) -> RefMap<'_, W> {
|
||||||
|
Ref::map(self.1.get(), |i| &mut i.widget)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mut(&self) -> RefMapMut<'_, W> {
|
||||||
|
let inner = self.1.get_mut();
|
||||||
|
if let Some(send) = &inner.send {
|
||||||
|
let _ = send.send(self.0);
|
||||||
|
}
|
||||||
|
RefMut::map(inner, |i| &mut i.widget)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn data(&self) -> Ref<'_, WidgetData<W>> {
|
||||||
|
self.1.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn data_mut(&self) -> RefMut<'_, WidgetData<W>> {
|
||||||
|
self.1.get_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_mut_quiet(&self) -> RefMapMut<'_, W> {
|
||||||
|
RefMut::map(self.1.get_mut(), |i| &mut i.widget)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_label(&self) -> RefMap<'_, String> {
|
||||||
|
Ref::map(self.1.get(), |i| &mut i.label)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_label(&self, label: impl Into<String>) {
|
||||||
|
self.1.get_mut().label = label.into();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TODO: THIS SHOULD ALWAYS BE 1, remove this probably (weak count might be nice though)
|
||||||
|
pub fn refs(&self) -> usize {
|
||||||
|
self.1.refs()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn weak(&self) -> WidgetRef<W> {
|
||||||
|
WidgetRef::new(self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type WRef<'a, W> = MappedRefGuard<'a, WidgetData<W>, W>;
|
||||||
|
pub type WRefMut<'a, W> = MappedRefGuardMut<'a, WidgetData<W>, W>;
|
||||||
|
|
||||||
|
impl<W: Widget> WidgetRef<W> {
|
||||||
|
fn handle(&self) -> Handle<WidgetData<W>> {
|
||||||
|
WIDGETS.get_type(self.0).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get<'a>(&self) -> WRef<'a, W> {
|
||||||
|
RefGuard::map(self.handle().get_take(), |i| &mut i.widget)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mut<'a>(&self) -> WRefMut<'a, W> {
|
||||||
|
let inner = self.handle().get_take_mut();
|
||||||
|
|
||||||
|
if let Some(send) = &inner.send {
|
||||||
|
let _ = send.send(self.0);
|
||||||
|
}
|
||||||
|
RefGuardMut::map(inner, |i| &mut i.widget)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: ?Sized + Widget> WidgetRef<W> {
|
||||||
|
pub fn data<'a>(&self) -> Option<RefGuard<'a, WidgetData<dyn Widget>>> {
|
||||||
|
Some(WIDGETS.get(self.0)?.get_take())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn data_mut(&self) -> Option<RefGuardMut<'_, WidgetData<dyn Widget>>> {
|
||||||
|
Some(WIDGETS.get(self.0)?.get_take_mut())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Widget + ?Sized + Unsize<dyn Widget>> WidgetRef<W> {
|
||||||
|
pub fn any(self) -> WidgetRef<dyn Widget> {
|
||||||
|
WidgetRef::new(self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: ?Sized> WidgetRef<W> {
|
||||||
|
fn new(id: WidgetId) -> Self {
|
||||||
|
Self(id, unsafe { MaybeUninit::zeroed().assume_init() })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn id(&self) -> WidgetId {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WidgetId {
|
||||||
|
/// THIS SHOULD ONLY BE CALLED FOR TEMP STUFF DURING PAINTING
|
||||||
|
pub(crate) fn strong(self) -> Option<WidgetHandle> {
|
||||||
|
Some(WidgetHandle(self, WIDGETS.get(self)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn weak(self) -> WidgetRef {
|
||||||
|
WidgetRef::new(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn map_event_managers(&self, f: impl Fn(Handle<dyn EventManager>)) {
|
||||||
|
let Some(data) = self.weak().data() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for m in data.event_managers() {
|
||||||
|
f(m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 WidgetRet: FnOnce(&mut Ui) -> WidgetHandle {}
|
||||||
|
impl<F: FnOnce(&mut Ui) -> WidgetHandle> WidgetRet for F {}
|
||||||
|
|
||||||
|
impl<W: Widget + ?Sized + Unsize<dyn Widget> + 'static> WidgetLike<IdTag> for WidgetHandle<W> {
|
||||||
|
type Widget = W;
|
||||||
|
fn add(self, _: &mut Ui) -> WidgetHandle<W> {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Widget + ?Sized + 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait IdLike<W> {
|
||||||
|
fn id(&self) -> WidgetId;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W> IdLike<W> for WidgetHandle<W> {
|
||||||
|
fn id(&self) -> WidgetId {
|
||||||
|
self.id()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W> IdLike<W> for WidgetRef<W> {
|
||||||
|
fn id(&self) -> WidgetId {
|
||||||
|
self.id()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetHandle<U>> for WidgetHandle<T> {}
|
||||||
|
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetRef<U>> for WidgetRef<T> {}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: ?Sized> Clone for WidgetRef<W> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
*self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: ?Sized> Copy for WidgetRef<W> {}
|
||||||
|
|
||||||
|
impl<W: ?Sized> PartialEq for WidgetRef<W> {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.0 == other.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unsafe impl<W: ?Sized> Send for WidgetRef<W> {}
|
||||||
|
unsafe impl<W: ?Sized> Sync for WidgetRef<W> {}
|
||||||
79
core/src/layout/widget/like.rs
Normal file
79
core/src/layout/widget/like.rs
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
use super::*;
|
||||||
|
use std::marker::Unsize;
|
||||||
|
|
||||||
|
pub trait WidgetLike<Tag> {
|
||||||
|
type Widget: Widget + ?Sized + Unsize<dyn Widget> + 'static;
|
||||||
|
|
||||||
|
fn add(self, ui: &mut Ui) -> WidgetHandle<Self::Widget>;
|
||||||
|
|
||||||
|
fn with_id<W2>(
|
||||||
|
self,
|
||||||
|
f: impl FnOnce(&mut Ui, WidgetHandle<Self::Widget>) -> WidgetHandle<W2>,
|
||||||
|
) -> impl WidgetIdFn<W2>
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
move |ui| {
|
||||||
|
let id = self.add(ui);
|
||||||
|
f(ui, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_root(self, ui: &mut Ui)
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
ui.set_root(self);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WidgetArr<const LEN: usize> {
|
||||||
|
pub arr: [WidgetHandle; LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const LEN: usize> WidgetArr<LEN> {
|
||||||
|
pub fn new(arr: [WidgetHandle; LEN]) -> Self {
|
||||||
|
Self { arr }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WidgetArrLike<const LEN: usize, Tag> {
|
||||||
|
fn ui(self, ui: &mut Ui) -> WidgetArr<LEN>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const LEN: usize> WidgetArrLike<LEN, ArrTag> for WidgetArr<LEN> {
|
||||||
|
fn ui(self, _: &mut Ui) -> WidgetArr<LEN> {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// I hate this language it's so bad why do I even use it
|
||||||
|
macro_rules! impl_widget_arr {
|
||||||
|
($n:expr;$($W:ident)*) => {
|
||||||
|
impl_widget_arr!($n;$($W)*;$(${concat($W,Tag)})*);
|
||||||
|
};
|
||||||
|
($n:expr;$($W:ident)*;$($Tag:ident)*) => {
|
||||||
|
impl<$($W: WidgetLike<$Tag>,$Tag,)*> WidgetArrLike<$n, ($($Tag,)*)> for ($($W,)*) {
|
||||||
|
fn ui(self, ui: &mut Ui) -> WidgetArr<$n> {
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
let ($($W,)*) = self;
|
||||||
|
WidgetArr::new(
|
||||||
|
[$($W.add(ui),)*],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_widget_arr!(1;A);
|
||||||
|
impl_widget_arr!(2;A B);
|
||||||
|
impl_widget_arr!(3;A B C);
|
||||||
|
impl_widget_arr!(4;A B C D);
|
||||||
|
impl_widget_arr!(5;A B C D E);
|
||||||
|
impl_widget_arr!(6;A B C D E F);
|
||||||
|
impl_widget_arr!(7;A B C D E F G);
|
||||||
|
impl_widget_arr!(8;A B C D E F G H);
|
||||||
|
impl_widget_arr!(9;A B C D E F G H I);
|
||||||
|
impl_widget_arr!(10;A B C D E F G H I J);
|
||||||
|
impl_widget_arr!(11;A B C D E F G H I J K);
|
||||||
|
impl_widget_arr!(12;A B C D E F G H I J K L);
|
||||||
65
core/src/layout/widget/mod.rs
Normal file
65
core/src/layout/widget/mod.rs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
mod data;
|
||||||
|
mod handle;
|
||||||
|
mod like;
|
||||||
|
mod tag;
|
||||||
|
mod widgets;
|
||||||
|
|
||||||
|
pub use data::*;
|
||||||
|
pub use handle::*;
|
||||||
|
pub use like::*;
|
||||||
|
pub use tag::*;
|
||||||
|
pub use widgets::*;
|
||||||
|
|
||||||
|
use crate::layout::{Len, Painter, SizeCtx, Ui};
|
||||||
|
|
||||||
|
pub trait Widget: 'static + Send + Sync {
|
||||||
|
fn draw(&mut self, painter: &mut Painter);
|
||||||
|
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len;
|
||||||
|
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Widget for () {
|
||||||
|
fn draw(&mut self, _: &mut Painter) {}
|
||||||
|
fn desired_width(&mut self, _: &mut SizeCtx) -> Len {
|
||||||
|
Len::ZERO
|
||||||
|
}
|
||||||
|
fn desired_height(&mut self, _: &mut SizeCtx) -> Len {
|
||||||
|
Len::ZERO
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 + ?Sized>: FnOnce(&mut Ui) -> W {}
|
||||||
|
impl<W: Widget, F: FnOnce(&mut Ui) -> W> WidgetFn<W> for F {}
|
||||||
|
|
||||||
|
impl<W: Widget, F: FnOnce(&mut Ui) -> W> WidgetLike<FnTag> for F {
|
||||||
|
type Widget = W;
|
||||||
|
fn add(self, ui: &mut Ui) -> WidgetHandle<W> {
|
||||||
|
self(ui).add(ui)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Widget> WidgetLike<WidgetTag> for W {
|
||||||
|
type Widget = W;
|
||||||
|
fn add(self, _: &mut Ui) -> WidgetHandle<W> {
|
||||||
|
WIDGETS.insert(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WidgetOption {
|
||||||
|
fn get(self, ui: &mut Ui) -> Option<WidgetHandle>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WidgetOption for () {
|
||||||
|
fn get(self, _: &mut Ui) -> Option<WidgetHandle> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F: FnOnce(&mut Ui) -> Option<WidgetHandle>> WidgetOption for F {
|
||||||
|
fn get(self, ui: &mut Ui) -> Option<WidgetHandle> {
|
||||||
|
self(ui)
|
||||||
|
}
|
||||||
|
}
|
||||||
5
core/src/layout/widget/tag.rs
Normal file
5
core/src/layout/widget/tag.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
pub struct WidgetTag;
|
||||||
|
pub struct FnTag;
|
||||||
|
pub struct IdTag;
|
||||||
|
pub struct IdFnTag;
|
||||||
|
pub struct ArrTag;
|
||||||
100
core/src/layout/widget/widgets.rs
Normal file
100
core/src/layout/widget/widgets.rs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
use std::sync::{Mutex, MutexGuard};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
layout::{
|
||||||
|
Widget, WidgetData, WidgetHandle,
|
||||||
|
widget::{SlotTy, WidgetId},
|
||||||
|
},
|
||||||
|
util::{Handle, WeakHandle},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) static WIDGETS: Widgets = Widgets::new();
|
||||||
|
pub(crate) struct Widgets(Mutex<Inner>);
|
||||||
|
|
||||||
|
pub fn total_widgets() -> usize {
|
||||||
|
WIDGETS.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WidgetSlot {
|
||||||
|
genr: SlotTy,
|
||||||
|
data: WeakHandle<WidgetData<dyn Widget + Sync + Send>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Inner {
|
||||||
|
cur_id: SlotTy,
|
||||||
|
vec: Vec<WidgetSlot>,
|
||||||
|
free: Vec<SlotTy>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Widgets {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self(Mutex::new(Inner {
|
||||||
|
cur_id: 0,
|
||||||
|
vec: Vec::new(),
|
||||||
|
free: Vec::new(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expect(&self) -> MutexGuard<'_, Inner> {
|
||||||
|
self.0.lock().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_type<W: 'static>(&self, id: WidgetId) -> Option<Handle<WidgetData<W>>> {
|
||||||
|
let slot = &self.expect().vec[id.i as usize];
|
||||||
|
if slot.genr != id.genr {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(unsafe { slot.data.clone().downcast() }.clone().strong()?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, id: WidgetId) -> Option<Handle<WidgetData<dyn Widget>>> {
|
||||||
|
let slot = &self.expect().vec[id.i as usize];
|
||||||
|
if slot.genr != id.genr {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(slot.data.clone().strong()?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert<W: Widget>(&self, widget: W) -> WidgetHandle<W> {
|
||||||
|
let mut s = self.expect();
|
||||||
|
let id = s
|
||||||
|
.free
|
||||||
|
.pop()
|
||||||
|
.map(|i| {
|
||||||
|
assert!(s.vec[i as usize].data.dropped());
|
||||||
|
WidgetId {
|
||||||
|
i,
|
||||||
|
genr: s.vec[i as usize].genr,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
let i = s.cur_id;
|
||||||
|
s.cur_id += 1;
|
||||||
|
WidgetId { i, genr: 0 }
|
||||||
|
});
|
||||||
|
let handle = WidgetHandle::new(id, widget);
|
||||||
|
let slot = WidgetSlot {
|
||||||
|
genr: id.genr,
|
||||||
|
data: handle.weak_inner(),
|
||||||
|
};
|
||||||
|
if id.i == s.vec.len() as SlotTy {
|
||||||
|
s.vec.push(slot);
|
||||||
|
} else {
|
||||||
|
s.vec[id.i as usize] = slot;
|
||||||
|
}
|
||||||
|
handle
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&self, id: WidgetId) {
|
||||||
|
let mut s = self.expect();
|
||||||
|
s.vec[id.i as usize].genr += 1;
|
||||||
|
s.free.push(id.i);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
let s = self.expect();
|
||||||
|
s.vec.len() - s.free.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,25 +11,11 @@
|
|||||||
#![feature(associated_type_defaults)]
|
#![feature(associated_type_defaults)]
|
||||||
#![feature(unsize)]
|
#![feature(unsize)]
|
||||||
#![feature(coerce_unsized)]
|
#![feature(coerce_unsized)]
|
||||||
|
#![feature(mapped_lock_guards)]
|
||||||
|
#![feature(ptr_metadata)]
|
||||||
|
|
||||||
mod attr;
|
pub mod layout;
|
||||||
mod event;
|
pub mod render;
|
||||||
mod num;
|
|
||||||
mod orientation;
|
|
||||||
mod primitive;
|
|
||||||
mod render;
|
|
||||||
mod ui;
|
|
||||||
mod widget;
|
|
||||||
|
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
pub use attr::*;
|
pub use image;
|
||||||
pub use event::*;
|
|
||||||
pub use num::*;
|
|
||||||
pub use orientation::*;
|
|
||||||
pub use primitive::*;
|
|
||||||
pub use render::*;
|
|
||||||
pub use ui::*;
|
|
||||||
pub use widget::*;
|
|
||||||
|
|
||||||
pub type UiColor = primitive::Color<u8>;
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::{UiRegion, util::Id};
|
use crate::{layout::UiRegion, util::Id};
|
||||||
use wgpu::*;
|
use wgpu::*;
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::num::NonZero;
|
use std::num::NonZero;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Ui,
|
layout::Ui,
|
||||||
render::{data::PrimitiveInstance, texture::GpuTextures, util::ArrBuf},
|
render::{data::PrimitiveInstance, texture::GpuTextures, util::ArrBuf},
|
||||||
util::HashMap,
|
util::HashMap,
|
||||||
};
|
};
|
||||||
@@ -61,10 +61,10 @@ impl UiRenderNode {
|
|||||||
|
|
||||||
pub fn update(&mut self, device: &Device, queue: &Queue, ui: &mut Ui) {
|
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.data.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.data.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;
|
||||||
@@ -101,10 +101,10 @@ impl UiRenderNode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut changed = false;
|
let mut changed = false;
|
||||||
changed |= self.textures.update(&mut ui.textures);
|
changed |= self.textures.update(&mut ui.data.textures);
|
||||||
if ui.masks.changed {
|
if ui.data.masks.changed {
|
||||||
ui.masks.changed = false;
|
ui.data.masks.changed = false;
|
||||||
self.masks.update(device, queue, &ui.masks[..]);
|
self.masks.update(device, queue, &ui.data.masks[..]);
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
if changed {
|
if changed {
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Color, UiRegion, WidgetId,
|
layout::{Color, UiRegion, WidgetId},
|
||||||
render::{
|
render::{
|
||||||
ArrBuf,
|
ArrBuf,
|
||||||
data::{MaskIdx, PrimitiveInstance},
|
data::{MaskIdx, PrimitiveInstance},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use bytemuck::Pod;
|
use bytemuck::Pod;
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
use wgpu::*;
|
use wgpu::*;
|
||||||
|
|
||||||
pub struct Primitives {
|
pub struct Primitives {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use image::{DynamicImage, EncodableLayout};
|
use image::{DynamicImage, EncodableLayout};
|
||||||
use wgpu::{util::DeviceExt, *};
|
use wgpu::{util::DeviceExt, *};
|
||||||
|
|
||||||
use crate::{TextureUpdate, Textures};
|
use crate::layout::{TextureUpdate, Textures};
|
||||||
|
|
||||||
pub struct GpuTextures {
|
pub struct GpuTextures {
|
||||||
device: Device,
|
device: Device,
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
use crate::{LayerId, MaskIdx, PrimitiveHandle, TextureHandle, UiRegion, WidgetId};
|
|
||||||
|
|
||||||
/// important non rendering data for retained drawing
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ActiveData {
|
|
||||||
pub id: WidgetId,
|
|
||||||
pub region: UiRegion,
|
|
||||||
pub parent: Option<WidgetId>,
|
|
||||||
pub textures: Vec<TextureHandle>,
|
|
||||||
pub primitives: Vec<PrimitiveHandle>,
|
|
||||||
pub children: Vec<WidgetId>,
|
|
||||||
pub mask: MaskIdx,
|
|
||||||
pub layer: LayerId,
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
use crate::{BothAxis, Len, UiVec2, WidgetId, util::HashMap};
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct Cache {
|
|
||||||
pub size: BothAxis<HashMap<WidgetId, (UiVec2, Len)>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Cache {
|
|
||||||
pub fn remove(&mut self, id: WidgetId) {
|
|
||||||
self.size.x.remove(&id);
|
|
||||||
self.size.y.remove(&id);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear(&mut self) {
|
|
||||||
self.size.x.clear();
|
|
||||||
self.size.y.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,235 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
ActiveData, Axis, EventsLike, Painter, SizeCtx, Ui, UiRegion, UiVec2, WidgetId,
|
|
||||||
render::MaskIdx,
|
|
||||||
util::{HashSet, forget_ref},
|
|
||||||
};
|
|
||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
|
|
||||||
/// state maintained between widgets during painting
|
|
||||||
pub struct DrawState<'a> {
|
|
||||||
pub(super) ui: &'a mut Ui,
|
|
||||||
pub(super) events: &'a mut dyn EventsLike,
|
|
||||||
draw_started: HashSet<WidgetId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> DrawState<'a> {
|
|
||||||
pub fn new(ui: &'a mut Ui, events: &'a mut dyn EventsLike) -> Self {
|
|
||||||
Self {
|
|
||||||
ui,
|
|
||||||
events,
|
|
||||||
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)
|
|
||||||
pub fn redraw(&mut self, id: WidgetId) {
|
|
||||||
self.widgets.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).len_axis(id, axis);
|
|
||||||
self.cache.size.axis_dyn(axis).insert(id, (outer, new));
|
|
||||||
if new != old {
|
|
||||||
self.redraw(pid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.draw_started.contains(&id) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let Some(active) = self.remove(id, false) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
self.draw_inner(
|
|
||||||
active.layer,
|
|
||||||
id,
|
|
||||||
active.region,
|
|
||||||
active.parent,
|
|
||||||
active.mask,
|
|
||||||
Some(active.children),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn size_ctx<'b>(&'b mut self, source: WidgetId, outer: UiVec2) -> SizeCtx<'b> {
|
|
||||||
SizeCtx {
|
|
||||||
source,
|
|
||||||
cache: &mut self.ui.cache,
|
|
||||||
text: &mut self.ui.text,
|
|
||||||
textures: &mut self.ui.textures,
|
|
||||||
widgets: &self.ui.widgets,
|
|
||||||
outer,
|
|
||||||
output_size: self.ui.output_size,
|
|
||||||
id: source,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn redraw_all(&mut self) {
|
|
||||||
// free all resources & cache
|
|
||||||
for (id, active) in self.ui.active.drain() {
|
|
||||||
let data = self.ui.widgets.data(id).unwrap();
|
|
||||||
self.events.undraw(data, &active);
|
|
||||||
}
|
|
||||||
self.ui.cache.clear();
|
|
||||||
self.ui.free(self.events);
|
|
||||||
self.layers.clear();
|
|
||||||
self.widgets.needs_redraw.clear();
|
|
||||||
|
|
||||||
if let Some(id) = &self.ui.root {
|
|
||||||
self.draw_inner(0, id.id(), UiRegion::FULL, None, MaskIdx::NONE, None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn draw_inner(
|
|
||||||
&mut self,
|
|
||||||
layer: usize,
|
|
||||||
id: WidgetId,
|
|
||||||
region: UiRegion,
|
|
||||||
parent: Option<WidgetId>,
|
|
||||||
mask: MaskIdx,
|
|
||||||
old_children: Option<Vec<WidgetId>>,
|
|
||||||
) {
|
|
||||||
let mut old_children = old_children.unwrap_or_default();
|
|
||||||
if let Some(active) = self.ui.active.get_mut(&id)
|
|
||||||
&& !self.ui.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).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(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut widget = painter.state.widgets.get_dyn_dynamic(id);
|
|
||||||
widget.draw(&mut painter);
|
|
||||||
drop(widget);
|
|
||||||
|
|
||||||
let Painter {
|
|
||||||
state: _,
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// update modules
|
|
||||||
let data = self.ui.widgets.data(id).unwrap();
|
|
||||||
self.events.draw(data, &active);
|
|
||||||
self.active.insert(id, active);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mov(&mut self, id: WidgetId, from: UiRegion, to: UiRegion) {
|
|
||||||
let active = self.ui.active.get_mut(&id).unwrap();
|
|
||||||
for h in &active.primitives {
|
|
||||||
let region = self.ui.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) -> 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 {
|
|
||||||
self.masks.remove(mask);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
active.textures.clear();
|
|
||||||
self.textures.free();
|
|
||||||
if undraw {
|
|
||||||
let data = self.ui.widgets.data(id).unwrap();
|
|
||||||
self.events.undraw(data, active);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
active
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove_rec(&mut self, id: WidgetId) -> Option<ActiveData> {
|
|
||||||
self.cache.remove(id);
|
|
||||||
let inst = self.remove(id, true);
|
|
||||||
if let Some(inst) = &inst {
|
|
||||||
for c in &inst.children {
|
|
||||||
self.remove_rec(*c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
inst
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for DrawState<'_> {
|
|
||||||
type Target = Ui;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
self.ui
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl DerefMut for DrawState<'_> {
|
|
||||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
||||||
self.ui
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,217 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
EventsLike, IdLike, Mask, PixelRegion, PrimitiveLayers, TextData, TextureHandle, Textures,
|
|
||||||
Widget, WidgetHandle, WidgetId, Widgets,
|
|
||||||
ui::draw_state::DrawState,
|
|
||||||
util::{HashMap, TrackedArena, Vec2},
|
|
||||||
};
|
|
||||||
use image::DynamicImage;
|
|
||||||
use std::{
|
|
||||||
ops::{Index, IndexMut},
|
|
||||||
sync::mpsc::{Receiver, channel},
|
|
||||||
};
|
|
||||||
|
|
||||||
mod active;
|
|
||||||
mod cache;
|
|
||||||
mod draw_state;
|
|
||||||
mod painter;
|
|
||||||
mod size;
|
|
||||||
mod state;
|
|
||||||
|
|
||||||
pub use active::*;
|
|
||||||
use cache::*;
|
|
||||||
pub use painter::Painter;
|
|
||||||
pub use size::*;
|
|
||||||
|
|
||||||
pub struct Ui {
|
|
||||||
// TODO: edit visibilities
|
|
||||||
pub widgets: Widgets,
|
|
||||||
|
|
||||||
// retained painter state
|
|
||||||
pub active: HashMap<WidgetId, ActiveData>,
|
|
||||||
pub layers: PrimitiveLayers,
|
|
||||||
pub textures: Textures,
|
|
||||||
pub text: TextData,
|
|
||||||
output_size: Vec2,
|
|
||||||
pub masks: TrackedArena<Mask, u32>,
|
|
||||||
pub cache: Cache,
|
|
||||||
|
|
||||||
pub root: Option<WidgetHandle>,
|
|
||||||
old_root: Option<WidgetId>,
|
|
||||||
recv: Receiver<WidgetId>,
|
|
||||||
resized: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait HasUi: Sized {
|
|
||||||
fn get(&self) -> &Ui;
|
|
||||||
fn get_mut(&mut self) -> &mut Ui;
|
|
||||||
fn ui(&self) -> &Ui {
|
|
||||||
self.get()
|
|
||||||
}
|
|
||||||
fn ui_mut(&mut self) -> &mut Ui {
|
|
||||||
self.get_mut()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HasUi for Ui {
|
|
||||||
fn get(&self) -> &Ui {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mut(&mut self) -> &mut Ui {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ui {
|
|
||||||
/// useful for debugging
|
|
||||||
pub fn set_label(&mut self, id: impl IdLike, label: String) {
|
|
||||||
self.widgets.data_mut(id.id()).unwrap().label = label;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn label(&self, id: impl IdLike) -> &String {
|
|
||||||
&self.widgets.data(id.id()).unwrap().label
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget>
|
|
||||||
where
|
|
||||||
I::Widget: Sized + Widget,
|
|
||||||
{
|
|
||||||
self.widgets.get(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget>
|
|
||||||
where
|
|
||||||
I::Widget: Sized + Widget,
|
|
||||||
{
|
|
||||||
self.widgets.get_mut(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_texture(&mut self, image: DynamicImage) -> TextureHandle {
|
|
||||||
self.textures.add(image)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resize(&mut self, size: impl Into<Vec2>) {
|
|
||||||
self.output_size = size.into();
|
|
||||||
self.resized = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update(&mut self, events: &mut dyn EventsLike) {
|
|
||||||
if !self.widgets.waiting.is_empty() {
|
|
||||||
let len = self.widgets.waiting.len();
|
|
||||||
let all: Vec<_> = self
|
|
||||||
.widgets
|
|
||||||
.waiting
|
|
||||||
.iter()
|
|
||||||
.map(|&w| format!("'{}' ({w:?})", self.label(w)))
|
|
||||||
.collect();
|
|
||||||
panic!(
|
|
||||||
"{len} widget(s) were never upgraded\n\
|
|
||||||
this is likely a memory leak; consider upgrading to strong if you plan on using it later\n\
|
|
||||||
weak widgets: {all:#?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if self.root_changed() {
|
|
||||||
DrawState::new(self, events).redraw_all();
|
|
||||||
self.old_root = self.root.as_ref().map(|r| r.id());
|
|
||||||
} else if self.widgets.has_updates() {
|
|
||||||
DrawState::new(self, events).redraw_updates();
|
|
||||||
}
|
|
||||||
if self.resized {
|
|
||||||
self.resized = false;
|
|
||||||
DrawState::new(self, events).redraw_all();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// free any resources that don't have references anymore
|
|
||||||
fn free(&mut self, events: &mut dyn EventsLike) {
|
|
||||||
for id in self.recv.try_iter() {
|
|
||||||
events.remove(id);
|
|
||||||
self.widgets.delete(id);
|
|
||||||
}
|
|
||||||
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 {
|
|
||||||
self.root_changed() || self.widgets.has_updates()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn num_widgets(&self) -> usize {
|
|
||||||
self.widgets.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn active_widgets(&self) -> usize {
|
|
||||||
self.active.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn debug_layers(&self) {
|
|
||||||
for ((idx, depth), primitives) in self.layers.iter_depth() {
|
|
||||||
let indent = " ".repeat(depth * 2);
|
|
||||||
let len = primitives.instances().len();
|
|
||||||
print!("{indent}{idx}: {len} primitives");
|
|
||||||
if len >= 1 {
|
|
||||||
print!(" ({})", primitives.instances()[0].binding);
|
|
||||||
}
|
|
||||||
println!();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn window_region(&self, id: &impl IdLike) -> Option<PixelRegion> {
|
|
||||||
let region = self.active.get(&id.id())?.region;
|
|
||||||
Some(region.to_px(self.output_size))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn debug(&self, label: &str) -> impl Iterator<Item = &ActiveData> {
|
|
||||||
self.active.iter().filter_map(move |(&id, inst)| {
|
|
||||||
let l = self.widgets.label(id);
|
|
||||||
if l == label { Some(inst) } else { None }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<I: IdLike> Index<I> for Ui
|
|
||||||
where
|
|
||||||
I::Widget: Sized + Widget,
|
|
||||||
{
|
|
||||||
type Output = I::Widget;
|
|
||||||
|
|
||||||
fn index(&self, id: I) -> &Self::Output {
|
|
||||||
self.get(&id).unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<I: IdLike> IndexMut<I> for Ui
|
|
||||||
where
|
|
||||||
I::Widget: Sized + Widget,
|
|
||||||
{
|
|
||||||
fn index_mut(&mut self, id: I) -> &mut Self::Output {
|
|
||||||
self.get_mut(&id).unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for Ui {
|
|
||||||
fn default() -> Self {
|
|
||||||
let (send, recv) = channel();
|
|
||||||
Self {
|
|
||||||
widgets: Widgets::new(send),
|
|
||||||
active: Default::default(),
|
|
||||||
layers: Default::default(),
|
|
||||||
masks: Default::default(),
|
|
||||||
text: Default::default(),
|
|
||||||
textures: Default::default(),
|
|
||||||
cache: Default::default(),
|
|
||||||
output_size: Vec2::ZERO,
|
|
||||||
root: None,
|
|
||||||
old_root: None,
|
|
||||||
recv,
|
|
||||||
resized: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
Axis, Len, RenderedText, Size, SizeCtx, TextAttrs, TextBuffer, TextData, TextureHandle,
|
|
||||||
UiRegion, Widget, WidgetHandle, WidgetId,
|
|
||||||
render::{Mask, MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst},
|
|
||||||
ui::draw_state::DrawState,
|
|
||||||
util::Vec2,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// makes your surfaces look pretty
|
|
||||||
pub struct Painter<'a, 'b> {
|
|
||||||
pub(super) state: &'a mut DrawState<'b>,
|
|
||||||
|
|
||||||
pub(super) region: UiRegion,
|
|
||||||
pub(super) mask: MaskIdx,
|
|
||||||
pub(super) textures: Vec<TextureHandle>,
|
|
||||||
pub(super) primitives: Vec<PrimitiveHandle>,
|
|
||||||
pub(super) children: Vec<WidgetId>,
|
|
||||||
pub layer: usize,
|
|
||||||
pub(super) id: WidgetId,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'c> Painter<'a, 'c> {
|
|
||||||
fn primitive_at<P: Primitive>(&mut self, primitive: P, region: UiRegion) {
|
|
||||||
let h = self.state.layers.write(
|
|
||||||
self.layer,
|
|
||||||
PrimitiveInst {
|
|
||||||
id: self.id,
|
|
||||||
primitive,
|
|
||||||
region,
|
|
||||||
mask_idx: self.mask,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if self.mask != MaskIdx::NONE {
|
|
||||||
// TODO: I have no clue if this works at all :joy:
|
|
||||||
self.state.masks.push_ref(self.mask);
|
|
||||||
}
|
|
||||||
self.primitives.push(h);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Writes a primitive to be rendered
|
|
||||||
pub fn primitive<P: Primitive>(&mut self, primitive: P) {
|
|
||||||
self.primitive_at(primitive, self.region)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn primitive_within<P: Primitive>(&mut self, primitive: P, region: UiRegion) {
|
|
||||||
self.primitive_at(primitive, region.within(&self.region));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_mask(&mut self, region: UiRegion) {
|
|
||||||
assert!(self.mask == MaskIdx::NONE);
|
|
||||||
self.mask = self.state.masks.push(Mask { region });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Draws a widget within this widget's region.
|
|
||||||
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: ?Sized>(&mut self, id: &WidgetHandle<W>, region: UiRegion) {
|
|
||||||
self.widget_at(id, region.within(&self.region));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn widget_at<W: ?Sized>(&mut self, id: &WidgetHandle<W>, region: UiRegion) {
|
|
||||||
self.children.push(id.id());
|
|
||||||
self.state
|
|
||||||
.draw_inner(self.layer, id.id(), region, Some(self.id), self.mask, None);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn texture_within(&mut self, handle: &TextureHandle, region: UiRegion) {
|
|
||||||
self.textures.push(handle.clone());
|
|
||||||
self.primitive_at(handle.primitive(), region.within(&self.region));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn texture(&mut self, handle: &TextureHandle) {
|
|
||||||
self.textures.push(handle.clone());
|
|
||||||
self.primitive(handle.primitive());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn texture_at(&mut self, handle: &TextureHandle, region: UiRegion) {
|
|
||||||
self.textures.push(handle.clone());
|
|
||||||
self.primitive_at(handle.primitive(), region);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// returns (handle, offset from top left)
|
|
||||||
pub fn render_text(&mut self, buffer: &mut TextBuffer, attrs: &TextAttrs) -> RenderedText {
|
|
||||||
self.state
|
|
||||||
.ui
|
|
||||||
.text
|
|
||||||
.draw(buffer, attrs, &mut self.state.ui.textures)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn region(&self) -> UiRegion {
|
|
||||||
self.region
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn size<W: ?Sized + Widget>(&mut self, id: &WidgetHandle<W>) -> Size {
|
|
||||||
self.size_ctx().size(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn len_axis<W: ?Sized + Widget>(&mut self, id: &WidgetHandle<W>, axis: Axis) -> Len {
|
|
||||||
match axis {
|
|
||||||
Axis::X => self.size_ctx().width(id),
|
|
||||||
Axis::Y => self.size_ctx().height(id),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn output_size(&self) -> Vec2 {
|
|
||||||
self.state.output_size
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn px_size(&mut self) -> Vec2 {
|
|
||||||
self.region.size().to_abs(self.state.output_size)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn text_data(&mut self) -> &mut TextData {
|
|
||||||
&mut self.state.text
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn child_layer(&mut self) {
|
|
||||||
self.layer = self.state.layers.child(self.layer);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn next_layer(&mut self) {
|
|
||||||
self.layer = self.state.layers.next(self.layer);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn label(&self) -> &str {
|
|
||||||
&self.state.widgets.data(self.id).unwrap().label
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn id(&self) -> &WidgetId {
|
|
||||||
&self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn size_ctx(&mut self) -> SizeCtx<'_> {
|
|
||||||
self.state.size_ctx(self.id, self.region.size())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
Axis, AxisT, IdLike, Len, RenderedText, Size, TextAttrs, TextBuffer, TextData, Textures,
|
|
||||||
UiVec2, WidgetAxisFns, WidgetId, Widgets, XAxis, YAxis, ui::cache::Cache, util::Vec2,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct SizeCtx<'a> {
|
|
||||||
pub text: &'a mut TextData,
|
|
||||||
pub textures: &'a mut Textures,
|
|
||||||
pub(super) source: WidgetId,
|
|
||||||
pub(super) widgets: &'a Widgets,
|
|
||||||
pub(super) cache: &'a mut Cache,
|
|
||||||
/// TODO: should this be pub? rn used for sized
|
|
||||||
pub outer: UiVec2,
|
|
||||||
pub(super) output_size: Vec2,
|
|
||||||
pub(super) id: WidgetId,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SizeCtx<'_> {
|
|
||||||
pub fn id(&self) -> &WidgetId {
|
|
||||||
&self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn source(&self) -> &WidgetId {
|
|
||||||
&self.source
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn len_inner<A: const AxisT>(&mut self, id: WidgetId) -> Len {
|
|
||||||
if let Some((_, len)) = self.cache.size.axis::<A>().get(&id) {
|
|
||||||
return *len;
|
|
||||||
}
|
|
||||||
let len = self
|
|
||||||
.widgets
|
|
||||||
.get_dyn_dynamic(id)
|
|
||||||
.desired_len::<A>(&mut SizeCtx {
|
|
||||||
text: self.text,
|
|
||||||
textures: self.textures,
|
|
||||||
source: self.source,
|
|
||||||
widgets: self.widgets,
|
|
||||||
cache: self.cache,
|
|
||||||
outer: self.outer,
|
|
||||||
output_size: self.output_size,
|
|
||||||
id,
|
|
||||||
});
|
|
||||||
self.cache.size.axis::<A>().insert(id, (self.outer, len));
|
|
||||||
len
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn width(&mut self, id: impl IdLike) -> Len {
|
|
||||||
self.len_inner::<XAxis>(id.id())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn height(&mut self, id: impl IdLike) -> Len {
|
|
||||||
self.len_inner::<YAxis>(id.id())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn len_axis(&mut self, id: impl IdLike, axis: Axis) -> Len {
|
|
||||||
match axis {
|
|
||||||
Axis::X => self.width(id),
|
|
||||||
Axis::Y => self.height(id),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn size(&mut self, id: impl IdLike) -> Size {
|
|
||||||
let id = id.id();
|
|
||||||
Size {
|
|
||||||
x: self.width(id),
|
|
||||||
y: self.height(id),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn px_size(&mut self) -> Vec2 {
|
|
||||||
self.outer.to_abs(self.output_size)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn output_size(&mut self) -> Vec2 {
|
|
||||||
self.output_size
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn draw_text(&mut self, buffer: &mut TextBuffer, attrs: &TextAttrs) -> RenderedText {
|
|
||||||
self.text.draw(buffer, attrs, self.textures)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn label(&self, id: WidgetId) -> &String {
|
|
||||||
self.widgets.label(id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
// pub struct DynState {
|
|
||||||
//
|
|
||||||
// }
|
|
||||||
@@ -7,7 +7,7 @@ pub struct Arena<T, I> {
|
|||||||
tracker: IdTracker<I>,
|
tracker: IdTracker<I>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, I: IdNum> Arena<T, I> {
|
impl<T, I: const IdNum> Arena<T, I> {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
data: Vec::new(),
|
data: Vec::new(),
|
||||||
@@ -36,7 +36,7 @@ impl<T, I: IdNum> Arena<T, I> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, I: IdNum> Default for Arena<T, I> {
|
impl<T, I: const IdNum> Default for Arena<T, I> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::new()
|
Self::new()
|
||||||
}
|
}
|
||||||
@@ -48,7 +48,7 @@ pub struct TrackedArena<T, I> {
|
|||||||
pub changed: bool,
|
pub changed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, I: IdNum> TrackedArena<T, I> {
|
impl<T, I: const IdNum> TrackedArena<T, I> {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Arena::default(),
|
inner: Arena::default(),
|
||||||
@@ -86,7 +86,7 @@ impl<T, I: IdNum> TrackedArena<T, I> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, I: IdNum> Default for TrackedArena<T, I> {
|
impl<T, I: const IdNum> Default for TrackedArena<T, I> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::new()
|
Self::new()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
use std::ops::{Deref, DerefMut};
|
|
||||||
|
|
||||||
pub struct DynBorrower<'a, T: ?Sized> {
|
|
||||||
data: &'a mut T,
|
|
||||||
borrowed: &'a mut bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, T: ?Sized> DynBorrower<'a, T> {
|
|
||||||
pub fn new(data: &'a mut T, borrowed: &'a mut bool) -> Self {
|
|
||||||
if *borrowed {
|
|
||||||
panic!("tried to mutably borrow the same thing twice");
|
|
||||||
}
|
|
||||||
Self { data, borrowed }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ?Sized> Drop for DynBorrower<'_, T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
*self.borrowed = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ?Sized> Deref for DynBorrower<'_, T> {
|
|
||||||
type Target = T;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
self.data
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ?Sized> DerefMut for DynBorrower<'_, T> {
|
|
||||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
||||||
self.data
|
|
||||||
}
|
|
||||||
}
|
|
||||||
227
core/src/util/handle.rs
Normal file
227
core/src/util/handle.rs
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
//! A helper type for Arc<Mutex<T>>
|
||||||
|
//! Currently there are mut versions (of Ref stuff) which don't do anything different under the hood,
|
||||||
|
//! leaving them in for now in case I decide RwLock is a desired feature
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
marker::Unsize,
|
||||||
|
ops::{CoerceUnsized, Deref, DerefMut},
|
||||||
|
sync::{Arc, MappedMutexGuard, Mutex, MutexGuard, Weak},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct Handle<T: ?Sized>(Arc<Mutex<T>>);
|
||||||
|
pub struct WeakHandle<T: ?Sized>(Weak<Mutex<T>>);
|
||||||
|
|
||||||
|
pub type Ref<'a, T> = MutexGuard<'a, T>;
|
||||||
|
pub type RefMut<'a, T> = MutexGuard<'a, T>;
|
||||||
|
|
||||||
|
pub type RefMap<'a, T> = MappedMutexGuard<'a, T>;
|
||||||
|
pub type RefMapMut<'a, T> = MappedMutexGuard<'a, T>;
|
||||||
|
|
||||||
|
impl<T: ?Sized> Handle<T> {
|
||||||
|
pub fn get(&self) -> Ref<'_, T> {
|
||||||
|
self.0.lock().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mut(&self) -> RefMut<'_, T> {
|
||||||
|
self.0.lock().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_take<'a>(self) -> RefGuard<'a, T> {
|
||||||
|
let handle = self;
|
||||||
|
RefGuard {
|
||||||
|
guard: unsafe {
|
||||||
|
std::mem::transmute::<MutexGuard<'_, T>, MutexGuard<'_, T>>(
|
||||||
|
handle.0.lock().unwrap(),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_take_mut<'a>(self) -> RefGuardMut<'a, T> {
|
||||||
|
let handle = self;
|
||||||
|
RefGuardMut {
|
||||||
|
guard: unsafe {
|
||||||
|
std::mem::transmute::<MutexGuard<'_, T>, MutexGuard<'_, T>>(
|
||||||
|
handle.0.lock().unwrap(),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refs(&self) -> usize {
|
||||||
|
Arc::strong_count(&self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn weak(&self) -> WeakHandle<T> {
|
||||||
|
WeakHandle(Arc::downgrade(&self.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// you must guarantee the type outside
|
||||||
|
/// ideally you check the typeid, but this is often used
|
||||||
|
/// when the trait object is wrapped one or more times
|
||||||
|
/// and you'd have to implement each one individually
|
||||||
|
pub unsafe fn downcast<U: 'static>(self) -> Handle<U>
|
||||||
|
where
|
||||||
|
T: 'static,
|
||||||
|
{
|
||||||
|
let raw: *const Mutex<T> = Arc::into_raw(self.0);
|
||||||
|
let raw: *const Mutex<U> = raw.cast();
|
||||||
|
Handle(unsafe { Arc::from_raw(raw) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> WeakHandle<T> {
|
||||||
|
pub fn strong(&self) -> Option<Handle<T>> {
|
||||||
|
Some(Handle(self.0.upgrade()?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dropped(&self) -> bool {
|
||||||
|
self.0.strong_count() == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Safety
|
||||||
|
/// you must guarantee the type outside
|
||||||
|
pub unsafe fn downcast<U: 'static>(self) -> WeakHandle<U>
|
||||||
|
where
|
||||||
|
T: 'static,
|
||||||
|
{
|
||||||
|
let raw: *const Mutex<T> = self.0.into_raw();
|
||||||
|
let raw: *const Mutex<U> = raw.cast();
|
||||||
|
WeakHandle(unsafe { Weak::from_raw(raw) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Clone for Handle<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Clone for WeakHandle<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Default> Default for Handle<T> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self(Default::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> From<T> for Handle<T> {
|
||||||
|
fn from(value: T) -> Self {
|
||||||
|
Self(Arc::new(Mutex::new(value)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Handle<U>> for Handle<T> {}
|
||||||
|
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WeakHandle<U>> for WeakHandle<T> {}
|
||||||
|
|
||||||
|
// yucky
|
||||||
|
|
||||||
|
// TODO: is drop order important here?
|
||||||
|
// something stupid could happen that I don't know about
|
||||||
|
// if handle is dropped before guard
|
||||||
|
pub struct RefGuard<'a, T: ?Sized> {
|
||||||
|
guard: MutexGuard<'a, T>,
|
||||||
|
handle: Handle<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RefGuardMut<'a, T: ?Sized> {
|
||||||
|
guard: MutexGuard<'a, T>,
|
||||||
|
handle: Handle<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MappedRefGuard<'a, T: ?Sized, U> {
|
||||||
|
guard: MappedMutexGuard<'a, U>,
|
||||||
|
handle: Handle<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MappedRefGuardMut<'a, T: ?Sized, U> {
|
||||||
|
guard: MappedMutexGuard<'a, U>,
|
||||||
|
handle: Handle<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: ?Sized> RefGuard<'a, T> {
|
||||||
|
pub fn map<U>(s: Self, f: impl FnOnce(&mut T) -> &mut U) -> MappedRefGuard<'a, T, U> {
|
||||||
|
MappedRefGuard {
|
||||||
|
guard: MutexGuard::map(s.guard, f),
|
||||||
|
handle: s.handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: ?Sized> RefGuardMut<'a, T> {
|
||||||
|
pub fn map<U>(s: Self, f: impl FnOnce(&mut T) -> &mut U) -> MappedRefGuardMut<'a, T, U> {
|
||||||
|
MappedRefGuardMut {
|
||||||
|
guard: MutexGuard::map(s.guard, f),
|
||||||
|
handle: s.handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: ?Sized, U> MappedRefGuard<'a, T, U> {
|
||||||
|
pub fn map<U2>(s: Self, f: impl FnOnce(&mut U) -> &mut U2) -> MappedRefGuard<'a, T, U2> {
|
||||||
|
MappedRefGuard {
|
||||||
|
guard: MappedMutexGuard::map(s.guard, f),
|
||||||
|
handle: s.handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: ?Sized, U> MappedRefGuardMut<'a, T, U> {
|
||||||
|
pub fn map<U2>(s: Self, f: impl FnOnce(&mut U) -> &mut U2) -> MappedRefGuardMut<'a, T, U2> {
|
||||||
|
MappedRefGuardMut {
|
||||||
|
guard: MappedMutexGuard::map(s.guard, f),
|
||||||
|
handle: s.handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Deref for RefGuard<'_, T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.guard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Deref for RefGuardMut<'_, T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.guard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> DerefMut for RefGuardMut<'_, T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.guard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized, U> Deref for MappedRefGuard<'_, T, U> {
|
||||||
|
type Target = U;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.guard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized, U> Deref for MappedRefGuardMut<'_, T, U> {
|
||||||
|
type Target = U;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.guard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized, U> DerefMut for MappedRefGuardMut<'_, T, U> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.guard
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
#[derive(Eq, Hash, PartialEq, Debug, Clone, Copy, bytemuck::Zeroable)]
|
#[derive(Eq, Hash, PartialEq, Debug, Clone, Copy, bytemuck::Zeroable)]
|
||||||
pub struct Id<I = u64>(I);
|
pub struct Id<I = u64>(I);
|
||||||
@@ -9,7 +11,14 @@ pub struct IdTracker<I = u64> {
|
|||||||
cur: Id<I>,
|
cur: Id<I>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<I: IdNum> IdTracker<I> {
|
impl<I: const IdNum> IdTracker<I> {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
free: Vec::new(),
|
||||||
|
cur: Id(I::first()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(clippy::should_implement_trait)]
|
#[allow(clippy::should_implement_trait)]
|
||||||
pub fn next(&mut self) -> Id<I> {
|
pub fn next(&mut self) -> Id<I> {
|
||||||
if let Some(id) = self.free.pop() {
|
if let Some(id) = self.free.pop() {
|
||||||
@@ -43,22 +52,19 @@ impl<I: IdNum> Id<I> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<I: IdNum> Default for IdTracker<I> {
|
impl<I: const IdNum> Default for IdTracker<I> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self::new()
|
||||||
free: Vec::new(),
|
|
||||||
cur: Id(I::first()),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait IdNum {
|
pub const trait IdNum {
|
||||||
fn first() -> Self;
|
fn first() -> Self;
|
||||||
fn next(&self) -> Self;
|
fn next(&self) -> Self;
|
||||||
fn idx(&self) -> usize;
|
fn idx(&self) -> usize;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IdNum for u64 {
|
impl const IdNum for u64 {
|
||||||
fn first() -> Self {
|
fn first() -> Self {
|
||||||
0
|
0
|
||||||
}
|
}
|
||||||
@@ -72,7 +78,7 @@ impl IdNum for u64 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IdNum for u32 {
|
impl const IdNum for u32 {
|
||||||
fn first() -> Self {
|
fn first() -> Self {
|
||||||
0
|
0
|
||||||
}
|
}
|
||||||
@@ -85,3 +91,33 @@ impl IdNum for u32 {
|
|||||||
*self as usize
|
*self as usize
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct StaticIdTracker<I = u64>(Mutex<IdTracker<I>>);
|
||||||
|
|
||||||
|
impl<I: const IdNum> StaticIdTracker<I> {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self(Mutex::new(IdTracker::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::should_implement_trait)]
|
||||||
|
pub fn next(&self) -> Id<I> {
|
||||||
|
let mut s = self.0.lock().unwrap();
|
||||||
|
if let Some(id) = s.free.pop() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
let next = s.cur.next();
|
||||||
|
std::mem::replace(&mut s.cur, next)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn free(&self, id: Id<I>) {
|
||||||
|
let mut s = self.0.lock().unwrap();
|
||||||
|
s.free.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<I: const IdNum> Default for StaticIdTracker<I> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,23 +1,17 @@
|
|||||||
mod arena;
|
mod arena;
|
||||||
mod borrow;
|
|
||||||
mod change;
|
mod change;
|
||||||
|
mod handle;
|
||||||
mod id;
|
mod id;
|
||||||
mod math;
|
mod math;
|
||||||
mod refcount;
|
mod refcount;
|
||||||
mod slot;
|
|
||||||
mod trust;
|
|
||||||
mod typemap;
|
|
||||||
mod vec2;
|
mod vec2;
|
||||||
|
|
||||||
pub use arena::*;
|
pub use arena::*;
|
||||||
pub use borrow::*;
|
|
||||||
pub use change::*;
|
pub use change::*;
|
||||||
|
pub use handle::*;
|
||||||
pub use id::*;
|
pub use id::*;
|
||||||
pub use math::*;
|
pub use math::*;
|
||||||
pub use refcount::*;
|
pub use refcount::*;
|
||||||
pub use slot::*;
|
|
||||||
pub use trust::*;
|
|
||||||
pub use typemap::*;
|
|
||||||
pub use vec2::*;
|
pub use vec2::*;
|
||||||
|
|
||||||
pub type HashMap<K, V> = fxhash::FxHashMap<K, V>;
|
pub type HashMap<K, V> = fxhash::FxHashMap<K, V>;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ impl RefCounter {
|
|||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self(Arc::new(0.into()))
|
Self(Arc::new(0.into()))
|
||||||
}
|
}
|
||||||
|
#[allow(unused)]
|
||||||
pub fn refs(&self) -> u32 {
|
pub fn refs(&self) -> u32 {
|
||||||
self.0.load(Ordering::Acquire)
|
self.0.load(Ordering::Acquire)
|
||||||
}
|
}
|
||||||
@@ -17,6 +18,7 @@ impl RefCounter {
|
|||||||
let refs = self.0.fetch_sub(1, Ordering::Release);
|
let refs = self.0.fetch_sub(1, Ordering::Release);
|
||||||
refs == 0
|
refs == 0
|
||||||
}
|
}
|
||||||
|
#[allow(unused)]
|
||||||
pub fn quiet_clone(&self) -> Self {
|
pub fn quiet_clone(&self) -> Self {
|
||||||
Self(self.0.clone())
|
Self(self.0.clone())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub struct SlotId {
|
|
||||||
idx: u32,
|
|
||||||
genr: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SlotVec<T> {
|
|
||||||
data: Vec<(u32, Option<T>)>,
|
|
||||||
free: Vec<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> SlotVec<T> {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
data: Default::default(),
|
|
||||||
free: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add(&mut self, x: T) -> SlotId {
|
|
||||||
if let Some(idx) = self.free.pop() {
|
|
||||||
let (genr, data) = &mut self.data[idx as usize];
|
|
||||||
*data = Some(x);
|
|
||||||
SlotId { idx, genr: *genr }
|
|
||||||
} else {
|
|
||||||
let idx = self.data.len() as u32;
|
|
||||||
let genr = 0;
|
|
||||||
self.data.push((genr, Some(x)));
|
|
||||||
SlotId { idx, genr }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn free(&mut self, id: SlotId) {
|
|
||||||
let (genr, data) = &mut self.data[id.idx as usize];
|
|
||||||
*genr += 1;
|
|
||||||
*data = None;
|
|
||||||
self.free.push(id.idx);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(&self, id: SlotId) -> Option<&T> {
|
|
||||||
let slot = &self.data[id.idx as usize];
|
|
||||||
if slot.0 != id.genr {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
slot.1.as_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_mut(&mut self, id: SlotId) -> Option<&mut T> {
|
|
||||||
let slot = &mut self.data[id.idx as usize];
|
|
||||||
if slot.0 != id.genr {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
slot.1.as_mut()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn len(&self) -> usize {
|
|
||||||
self.data.len() - self.free.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
self.len() == 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Default for SlotVec<T> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
#[allow(clippy::missing_safety_doc)]
|
|
||||||
pub unsafe fn forget_ref<'a, T>(x: &T) -> &'a T {
|
|
||||||
unsafe { std::mem::transmute::<&T, &T>(x) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::missing_safety_doc)]
|
|
||||||
pub unsafe fn forget_mut<'a, T>(x: &mut T) -> &'a mut T {
|
|
||||||
unsafe { std::mem::transmute::<&mut T, &mut T>(x) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::mut_from_ref, clippy::missing_safety_doc)]
|
|
||||||
pub unsafe fn to_mut<T>(x: &T) -> &mut T {
|
|
||||||
#[allow(mutable_transmutes)]
|
|
||||||
unsafe {
|
|
||||||
std::mem::transmute::<&T, &mut T>(x)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
use crate::util::HashMap;
|
|
||||||
use std::{
|
|
||||||
any::TypeId,
|
|
||||||
marker::Unsize,
|
|
||||||
ops::{Deref, DerefMut},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct TypeMap<Trait: ?Sized> {
|
|
||||||
map: HashMap<TypeId, Box<Trait>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Trait: ?Sized> TypeMap<Trait> {
|
|
||||||
pub fn set_type<T: Unsize<Trait> + 'static>(&mut self, val: T) {
|
|
||||||
self.map
|
|
||||||
.insert(TypeId::of::<T>(), Box::new(val) as Box<Trait>);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn type_mut<T: Unsize<Trait> + 'static>(&mut self) -> Option<&mut T> {
|
|
||||||
Some(Self::convert_mut(self.map.get_mut(&TypeId::of::<T>())?))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn type_or_default<T: Default + Unsize<Trait> + 'static>(&mut self) -> &mut T {
|
|
||||||
Self::convert_mut(
|
|
||||||
self.map
|
|
||||||
.entry(TypeId::of::<T>())
|
|
||||||
.or_insert(Box::new(T::default()) as Box<Trait>),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn convert_mut<T: Unsize<Trait>>(entry: &mut Box<Trait>) -> &mut T {
|
|
||||||
// allegedly this is just what Any does...
|
|
||||||
unsafe { &mut *(entry.as_mut() as *mut Trait as *mut T) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ?Sized> Deref for TypeMap<T> {
|
|
||||||
type Target = HashMap<TypeId, Box<T>>;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
&self.map
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ?Sized> DerefMut for TypeMap<T> {
|
|
||||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
||||||
&mut self.map
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ?Sized> Default for TypeMap<T> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
map: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
use std::any::TypeId;
|
|
||||||
|
|
||||||
use crate::{Widget, util::HashSet};
|
|
||||||
|
|
||||||
pub struct WidgetData {
|
|
||||||
pub widget: Box<dyn Widget>,
|
|
||||||
pub label: String,
|
|
||||||
pub event_mgrs: HashSet<TypeId>,
|
|
||||||
/// dynamic borrow checking
|
|
||||||
pub borrowed: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WidgetData {
|
|
||||||
pub fn new<W: Widget>(widget: W) -> Self {
|
|
||||||
let mut label = std::any::type_name::<W>().to_string();
|
|
||||||
if let (Some(first), Some(last)) = (label.find(":"), label.rfind(":")) {
|
|
||||||
label = label.split_at(first).0.to_string() + "::" + label.split_at(last + 1).1;
|
|
||||||
}
|
|
||||||
Self {
|
|
||||||
widget: Box::new(widget),
|
|
||||||
label,
|
|
||||||
borrowed: false,
|
|
||||||
event_mgrs: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
use std::{marker::Unsize, ops::CoerceUnsized, sync::mpsc::Sender};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
HasUi, Widget,
|
|
||||||
util::{RefCounter, SlotId},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub type WidgetId = SlotId;
|
|
||||||
|
|
||||||
/// An identifier for a widget that can index a UI or event ctx to get it.
|
|
||||||
/// This is a strong handle that does not impl Clone, and when it is dropped,
|
|
||||||
/// 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?
|
|
||||||
pub struct WidgetHandle<W: ?Sized = dyn Widget> {
|
|
||||||
pub(super) id: WidgetId,
|
|
||||||
counter: RefCounter,
|
|
||||||
send: Sender<WidgetId>,
|
|
||||||
ty: *const W,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A weak handle to a widget.
|
|
||||||
/// Will not keep it alive, but can still be used for indexing like WidgetHandle.
|
|
||||||
pub struct WidgetRef<W: ?Sized = dyn Widget> {
|
|
||||||
pub(super) id: WidgetId,
|
|
||||||
#[allow(unused)]
|
|
||||||
ty: *const W,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct WidgetHandles<W: ?Sized = dyn Widget> {
|
|
||||||
pub h: WidgetHandle<W>,
|
|
||||||
pub r: WidgetRef<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: WidgetId, send: Sender<WidgetId>) -> Self {
|
|
||||||
Self {
|
|
||||||
id,
|
|
||||||
counter: RefCounter::new(),
|
|
||||||
send,
|
|
||||||
ty: null_ptr(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn id(&self) -> WidgetId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refs(&self) -> u32 {
|
|
||||||
self.counter.refs()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn weak(&self) -> WidgetRef<W> {
|
|
||||||
let Self { ty, id, .. } = *self;
|
|
||||||
WidgetRef { ty, id }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn handles(self) -> WidgetHandles<W> {
|
|
||||||
let r = self.weak();
|
|
||||||
WidgetHandles { h: self, r }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: ?Sized> WidgetRef<W> {
|
|
||||||
pub(crate) fn new(id: WidgetId) -> Self {
|
|
||||||
Self { id, ty: null_ptr() }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn id(&self) -> WidgetId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
#[track_caller]
|
|
||||||
pub fn upgrade(self, ui: &mut impl HasUi) -> WidgetHandle<W> {
|
|
||||||
ui.ui_mut().widgets.upgrade(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: ?Sized> Drop for WidgetHandle<W> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if self.counter.drop() {
|
|
||||||
let _ = self.send.send(self.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WidgetIdFn<State, W: ?Sized = dyn Widget>: FnOnce(&mut State) -> WidgetRef<W> {}
|
|
||||||
impl<State, W: ?Sized, F: FnOnce(&mut State) -> WidgetRef<W>> WidgetIdFn<State, W> for F {}
|
|
||||||
|
|
||||||
pub trait IdLike {
|
|
||||||
type Widget: ?Sized;
|
|
||||||
fn id(&self) -> WidgetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: ?Sized> IdLike for &WidgetHandle<W> {
|
|
||||||
type Widget = W;
|
|
||||||
fn id(&self) -> WidgetId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: ?Sized> IdLike for WidgetHandle<W> {
|
|
||||||
type Widget = W;
|
|
||||||
fn id(&self) -> WidgetId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: ?Sized> IdLike for WidgetRef<W> {
|
|
||||||
type Widget = W;
|
|
||||||
fn id(&self) -> WidgetId {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IdLike for WidgetId {
|
|
||||||
type Widget = dyn Widget;
|
|
||||||
fn id(&self) -> WidgetId {
|
|
||||||
*self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetHandle<U>> for WidgetHandle<T> {}
|
|
||||||
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<WidgetRef<U>> for WidgetRef<T> {}
|
|
||||||
|
|
||||||
impl<W: ?Sized> Clone for WidgetRef<W> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
*self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<W: ?Sized> Copy for WidgetRef<W> {}
|
|
||||||
impl<W: ?Sized> PartialEq for WidgetRef<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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, W: Widget + 'a, State: HasUi> FnOnce<(&'a mut State,)> for WidgetRef<W> {
|
|
||||||
type Output = &'a mut W;
|
|
||||||
|
|
||||||
extern "rust-call" fn call_once(self, args: (&'a mut State,)) -> Self::Output {
|
|
||||||
&mut args.0.ui_mut()[self]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn null_ptr<W: ?Sized>() -> *const W {
|
|
||||||
if size_of::<&W>() == size_of::<*const dyn Widget>() {
|
|
||||||
let w: *const dyn Widget = &();
|
|
||||||
unsafe { std::mem::transmute_copy(&w) }
|
|
||||||
} else {
|
|
||||||
unsafe { std::mem::transmute_copy(&[0usize; 1]) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
use crate::{HasUi, Ui};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use std::marker::Unsize;
|
|
||||||
|
|
||||||
pub trait StateLike<State> {
|
|
||||||
fn as_state(&mut self) -> &mut State;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StateLike<Ui> for Ui {
|
|
||||||
fn as_state(&mut self) -> &mut Ui {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WidgetLike<State: HasUi + StateLike<State>, Tag>: Sized {
|
|
||||||
type Widget: Widget + ?Sized + Unsize<dyn Widget>;
|
|
||||||
|
|
||||||
fn add(self, state: &mut impl StateLike<State>) -> WidgetRef<Self::Widget>;
|
|
||||||
|
|
||||||
fn add_strong(self, state: &mut impl StateLike<State>) -> WidgetHandle<Self::Widget> {
|
|
||||||
self.add(state).upgrade(state.as_state().ui_mut())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn with_id<W2>(
|
|
||||||
self,
|
|
||||||
f: impl FnOnce(&mut State, WidgetRef<Self::Widget>) -> WidgetRef<W2>,
|
|
||||||
) -> impl WidgetIdFn<State, W2> {
|
|
||||||
move |state| {
|
|
||||||
let id = self.add(state);
|
|
||||||
f(state, id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_root(self, state: &mut impl StateLike<State>) {
|
|
||||||
let id = self.add(state);
|
|
||||||
let ui = state.as_state().ui_mut();
|
|
||||||
ui.root = Some(id.upgrade(ui));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handles(self, state: &mut impl StateLike<State>) -> WidgetHandles<Self::Widget> {
|
|
||||||
self.add(state).upgrade(state.as_state().ui_mut()).handles()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WidgetArrLike<State, const LEN: usize, Tag> {
|
|
||||||
#[track_caller]
|
|
||||||
fn add(self, state: &mut impl StateLike<State>) -> WidgetArr<LEN>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State, const LEN: usize> WidgetArrLike<State, LEN, ArrTag> for WidgetArr<LEN> {
|
|
||||||
fn add(self, _: &mut impl StateLike<State>) -> WidgetArr<LEN> {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// variadic generics please save us
|
|
||||||
macro_rules! impl_widget_arr {
|
|
||||||
($n:expr;$($W:ident)*) => {
|
|
||||||
impl_widget_arr!($n;$($W)*;$(${concat($W,Tag)})*);
|
|
||||||
};
|
|
||||||
($n:expr;$($W:ident)*;$($Tag:ident)*) => {
|
|
||||||
impl<State: HasUi + StateLike<State>, $($W: WidgetLike<State, $Tag>,$Tag,)*> WidgetArrLike<State, $n, ($($Tag,)*)> for ($($W,)*) {
|
|
||||||
fn add(self, state: &mut impl StateLike<State>) -> WidgetArr<$n> {
|
|
||||||
#[allow(non_snake_case)]
|
|
||||||
let ($($W,)*) = self;
|
|
||||||
WidgetArr::new(
|
|
||||||
[$($W.add(state).upgrade(state.as_state().ui_mut()),)*],
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
impl_widget_arr!(1;A);
|
|
||||||
impl_widget_arr!(2;A B);
|
|
||||||
impl_widget_arr!(3;A B C);
|
|
||||||
impl_widget_arr!(4;A B C D);
|
|
||||||
impl_widget_arr!(5;A B C D E);
|
|
||||||
impl_widget_arr!(6;A B C D E F);
|
|
||||||
impl_widget_arr!(7;A B C D E F G);
|
|
||||||
impl_widget_arr!(8;A B C D E F G H);
|
|
||||||
impl_widget_arr!(9;A B C D E F G H I);
|
|
||||||
impl_widget_arr!(10;A B C D E F G H I J);
|
|
||||||
impl_widget_arr!(11;A B C D E F G H I J K);
|
|
||||||
impl_widget_arr!(12;A B C D E F G H I J K L);
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
use crate::{Axis, AxisT, Len, Painter, SizeCtx};
|
|
||||||
use std::any::Any;
|
|
||||||
|
|
||||||
mod data;
|
|
||||||
mod handle;
|
|
||||||
mod like;
|
|
||||||
mod tag;
|
|
||||||
mod widgets;
|
|
||||||
|
|
||||||
pub use data::*;
|
|
||||||
pub use handle::*;
|
|
||||||
pub use like::*;
|
|
||||||
pub use tag::*;
|
|
||||||
pub use widgets::*;
|
|
||||||
|
|
||||||
pub trait Widget: Any {
|
|
||||||
fn draw(&mut self, painter: &mut Painter);
|
|
||||||
fn desired_width(&mut self, ctx: &mut SizeCtx) -> Len;
|
|
||||||
fn desired_height(&mut self, ctx: &mut SizeCtx) -> Len;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WidgetAxisFns {
|
|
||||||
fn desired_len<A: AxisT>(&mut self, ctx: &mut SizeCtx) -> Len;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: Widget + ?Sized> WidgetAxisFns for W {
|
|
||||||
fn desired_len<A: AxisT>(&mut self, ctx: &mut SizeCtx) -> Len {
|
|
||||||
match A::get() {
|
|
||||||
Axis::X => self.desired_width(ctx),
|
|
||||||
Axis::Y => self.desired_height(ctx),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Widget for () {
|
|
||||||
fn draw(&mut self, _: &mut Painter) {}
|
|
||||||
fn desired_width(&mut self, _: &mut SizeCtx) -> Len {
|
|
||||||
Len::ZERO
|
|
||||||
}
|
|
||||||
fn desired_height(&mut self, _: &mut SizeCtx) -> Len {
|
|
||||||
Len::ZERO
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl dyn Widget {
|
|
||||||
pub fn as_any(&self) -> &dyn Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_any_mut(&mut self) -> &mut dyn Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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<State, W: Widget + ?Sized>: FnOnce(&mut State) -> W {}
|
|
||||||
impl<State, W: Widget + ?Sized, F: FnOnce(&mut State) -> W> WidgetFn<State, W> for F {}
|
|
||||||
|
|
||||||
pub struct WidgetArr<const LEN: usize> {
|
|
||||||
pub arr: [WidgetHandle; LEN],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<const LEN: usize> WidgetArr<LEN> {
|
|
||||||
pub fn new(arr: [WidgetHandle; LEN]) -> Self {
|
|
||||||
Self { arr }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WidgetOption<State> {
|
|
||||||
fn get(self, state: &mut State) -> Option<WidgetHandle>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State> WidgetOption<State> for () {
|
|
||||||
fn get(self, _: &mut State) -> Option<WidgetHandle> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State, F: FnOnce(&mut State) -> Option<WidgetHandle>> WidgetOption<State> for F {
|
|
||||||
fn get(self, state: &mut State) -> Option<WidgetHandle> {
|
|
||||||
self(state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
use super::*;
|
|
||||||
use crate::HasUi;
|
|
||||||
use std::marker::Unsize;
|
|
||||||
|
|
||||||
pub struct WidgetTag;
|
|
||||||
impl<State: HasUi + StateLike<State>, W: Widget> WidgetLike<State, WidgetTag> for W {
|
|
||||||
type Widget = W;
|
|
||||||
fn add(self, state: &mut impl StateLike<State>) -> WidgetRef<W> {
|
|
||||||
state.as_state().get_mut().widgets.add_weak(self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct FnTag;
|
|
||||||
impl<State: HasUi + StateLike<State>, W: Widget, F: FnOnce(&mut State) -> W>
|
|
||||||
WidgetLike<State, FnTag> for F
|
|
||||||
{
|
|
||||||
type Widget = W;
|
|
||||||
fn add(self, state: &mut impl StateLike<State>) -> WidgetRef<W> {
|
|
||||||
self(state.as_state()).add(state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WidgetFnTrait<State> {
|
|
||||||
type Widget: Widget;
|
|
||||||
fn run(self, state: &mut State) -> Self::Widget;
|
|
||||||
}
|
|
||||||
pub struct FnTraitTag;
|
|
||||||
impl<State: HasUi + StateLike<State>, T: WidgetFnTrait<State>> WidgetLike<State, FnTraitTag> for T {
|
|
||||||
type Widget = T::Widget;
|
|
||||||
#[track_caller]
|
|
||||||
fn add(self, state: &mut impl StateLike<State>) -> WidgetRef<T::Widget> {
|
|
||||||
self.run(state.as_state()).add(state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct IdTag;
|
|
||||||
impl<State: HasUi + StateLike<State>, W: ?Sized + Widget + Unsize<dyn Widget>>
|
|
||||||
WidgetLike<State, IdTag> for WidgetRef<W>
|
|
||||||
{
|
|
||||||
type Widget = W;
|
|
||||||
fn add(self, _: &mut impl StateLike<State>) -> WidgetRef<W> {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct IdFnTag;
|
|
||||||
impl<
|
|
||||||
State: HasUi + StateLike<State>,
|
|
||||||
W: ?Sized + Widget + Unsize<dyn Widget>,
|
|
||||||
F: FnOnce(&mut State) -> WidgetRef<W>,
|
|
||||||
> WidgetLike<State, IdFnTag> for F
|
|
||||||
{
|
|
||||||
type Widget = W;
|
|
||||||
fn add(self, state: &mut impl StateLike<State>) -> WidgetRef<W> {
|
|
||||||
self(state.as_state())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ArrTag;
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
use std::sync::mpsc::Sender;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
IdLike, Widget, WidgetData, WidgetHandle, WidgetId, WidgetRef,
|
|
||||||
util::{DynBorrower, HashSet, SlotVec, forget_mut, to_mut},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Widgets {
|
|
||||||
pub needs_redraw: HashSet<WidgetId>,
|
|
||||||
vec: SlotVec<WidgetData>,
|
|
||||||
send: Sender<WidgetId>,
|
|
||||||
pub(crate) waiting: HashSet<WidgetId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Widgets {
|
|
||||||
pub fn new(send: Sender<WidgetId>) -> Self {
|
|
||||||
Self {
|
|
||||||
needs_redraw: Default::default(),
|
|
||||||
vec: Default::default(),
|
|
||||||
waiting: Default::default(),
|
|
||||||
send,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn has_updates(&self) -> bool {
|
|
||||||
!self.needs_redraw.is_empty()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_dyn(&self, id: WidgetId) -> Option<&dyn Widget> {
|
|
||||||
Some(self.vec.get(id)?.widget.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_dyn_mut(&mut self, id: WidgetId) -> Option<&mut dyn Widget> {
|
|
||||||
self.needs_redraw.insert(id);
|
|
||||||
Some(self.vec.get_mut(id)?.widget.as_mut())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// get_dyn but dynamic borrow checking of widgets
|
|
||||||
/// lets you do recursive (tree) operations, like the painter does
|
|
||||||
pub(crate) fn get_dyn_dynamic<'a>(&self, id: WidgetId) -> WidgetWrapper<'a> {
|
|
||||||
// SAFETY: must guarantee no other mutable references to this widget exist
|
|
||||||
// done through the borrow variable
|
|
||||||
let data = unsafe { forget_mut(to_mut(self.vec.get(id).unwrap())) };
|
|
||||||
if data.borrowed {
|
|
||||||
panic!("tried to mutably borrow the same widget twice");
|
|
||||||
}
|
|
||||||
WidgetWrapper::new(data.widget.as_mut(), &mut data.borrowed)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get<I: IdLike>(&self, id: &I) -> Option<&I::Widget>
|
|
||||||
where
|
|
||||||
I::Widget: Sized + Widget,
|
|
||||||
{
|
|
||||||
self.get_dyn(id.id())?.as_any().downcast_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_mut<I: IdLike>(&mut self, id: &I) -> Option<&mut I::Widget>
|
|
||||||
where
|
|
||||||
I::Widget: Sized + Widget,
|
|
||||||
{
|
|
||||||
self.get_dyn_mut(id.id())?.as_any_mut().downcast_mut()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_strong<W: Widget>(&mut self, widget: W) -> WidgetHandle<W> {
|
|
||||||
let id = self.vec.add(WidgetData::new(widget));
|
|
||||||
WidgetHandle::new(id, self.send.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_weak<W: Widget>(&mut self, widget: W) -> WidgetRef<W> {
|
|
||||||
let id = self.vec.add(WidgetData::new(widget));
|
|
||||||
self.waiting.insert(id);
|
|
||||||
WidgetRef::new(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[track_caller]
|
|
||||||
pub fn upgrade<W: ?Sized>(&mut self, rf: WidgetRef<W>) -> WidgetHandle<W> {
|
|
||||||
if !self.waiting.remove(&rf.id()) {
|
|
||||||
let label = self.label(rf);
|
|
||||||
let id = rf.id();
|
|
||||||
panic!("widget '{label}' ({id:?}) was already added\ncannot add a widget twice; consider creating two")
|
|
||||||
}
|
|
||||||
WidgetHandle::new(rf.id(), self.send.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn data(&self, id: impl IdLike) -> Option<&WidgetData> {
|
|
||||||
self.vec.get(id.id())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn label(&self, id: impl IdLike) -> &String {
|
|
||||||
&self.data(id.id()).unwrap().label
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn data_mut(&mut self, id: impl IdLike) -> Option<&mut WidgetData> {
|
|
||||||
self.vec.get_mut(id.id())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete(&mut self, id: impl IdLike) {
|
|
||||||
self.vec.free(id.id());
|
|
||||||
// not sure if there's any point in this
|
|
||||||
// self.updates.remove(&id);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::len_without_is_empty)]
|
|
||||||
pub fn len(&self) -> usize {
|
|
||||||
self.vec.len()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub type WidgetWrapper<'a> = DynBorrower<'a, dyn Widget>;
|
|
||||||
@@ -1,20 +1,14 @@
|
|||||||
use iris::prelude::*;
|
use iris::{prelude::*};
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
App::<State>::run();
|
DefaultApp::<State>::run();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[default_ui_state]
|
struct State;
|
||||||
struct State {}
|
|
||||||
|
|
||||||
impl DefaultAppState for State {
|
impl DefaultAppState for State {
|
||||||
fn new(ui_state: DefaultUiState, _proxy: Proxy<Self::Event>) -> Self {
|
fn new(ui: &mut Ui, _state: &UiState, _proxy: Proxy<Self::Event>) -> Self {
|
||||||
let mut ui = Ui::new();
|
rect(Color::RED).set_root(ui);
|
||||||
rect(Color::RED).set_root(&mut ui);
|
Self
|
||||||
Self {
|
|
||||||
ui,
|
|
||||||
ui_state,
|
|
||||||
events: EventManager::default(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ version.workspace = true
|
|||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
proc-macro2 = "1.0.103"
|
|
||||||
quote = "1.0.42"
|
quote = "1.0.42"
|
||||||
syn = { version = "2.0.111", features = ["full"] }
|
syn = { version = "2.0.111", features = ["full"] }
|
||||||
|
|
||||||
|
|||||||
125
macro/src/lib.rs
125
macro/src/lib.rs
@@ -2,18 +2,15 @@ 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, Fields, FieldsNamed, GenericParam, Generics, Ident, ItemStruct,
|
Attribute, Block, Ident, ItemTrait, Signature, Token, Visibility,
|
||||||
ItemTrait, Meta, Signature, Token, Visibility,
|
|
||||||
parse::{Parse, ParseStream, Result},
|
parse::{Parse, ParseStream, Result},
|
||||||
parse_macro_input, parse_quote,
|
parse_macro_input, parse_quote,
|
||||||
spanned::Spanned,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Input {
|
struct Input {
|
||||||
attrs: Vec<Attribute>,
|
attrs: Vec<Attribute>,
|
||||||
vis: Visibility,
|
vis: Visibility,
|
||||||
name: Ident,
|
name: Ident,
|
||||||
generics: Generics,
|
|
||||||
fns: Vec<InputFn>,
|
fns: Vec<InputFn>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,7 +25,6 @@ impl Parse for Input {
|
|||||||
let vis = input.parse()?;
|
let vis = input.parse()?;
|
||||||
input.parse::<Token![trait]>()?;
|
input.parse::<Token![trait]>()?;
|
||||||
let name = input.parse()?;
|
let name = input.parse()?;
|
||||||
let generics = input.parse::<Generics>()?;
|
|
||||||
input.parse::<Token![;]>()?;
|
input.parse::<Token![;]>()?;
|
||||||
let mut fns = Vec::new();
|
let mut fns = Vec::new();
|
||||||
while !input.is_empty() {
|
while !input.is_empty() {
|
||||||
@@ -43,7 +39,6 @@ impl Parse for Input {
|
|||||||
attrs,
|
attrs,
|
||||||
vis,
|
vis,
|
||||||
name,
|
name,
|
||||||
generics,
|
|
||||||
fns,
|
fns,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -55,7 +50,6 @@ pub fn widget_trait(input: TokenStream) -> TokenStream {
|
|||||||
attrs,
|
attrs,
|
||||||
vis,
|
vis,
|
||||||
name,
|
name,
|
||||||
mut generics,
|
|
||||||
fns,
|
fns,
|
||||||
} = parse_macro_input!(input as Input);
|
} = parse_macro_input!(input as Input);
|
||||||
|
|
||||||
@@ -65,128 +59,19 @@ pub fn widget_trait(input: TokenStream) -> TokenStream {
|
|||||||
.map(|InputFn { sig, body }| quote! { #sig #body })
|
.map(|InputFn { sig, body }| quote! { #sig #body })
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let Some(GenericParam::Type(state)) = generics.params.first() else {
|
|
||||||
return Error::new(name.span(), "expected state generic parameter")
|
|
||||||
.into_compile_error()
|
|
||||||
.into();
|
|
||||||
};
|
|
||||||
|
|
||||||
let state = &state.ident;
|
|
||||||
|
|
||||||
generics
|
|
||||||
.params
|
|
||||||
.push(parse_quote!(WL: WidgetLike<#state, Tag>));
|
|
||||||
generics.params.push(parse_quote!(Tag));
|
|
||||||
|
|
||||||
let mut trai: ItemTrait = parse_quote!(
|
let mut trai: ItemTrait = parse_quote!(
|
||||||
#vis trait #name #generics {
|
#vis trait #name<WL: WidgetLike<Tag>, Tag> {
|
||||||
#(#sigs;)*
|
#(#sigs;)*
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
trai.attrs = attrs;
|
trai.attrs = attrs;
|
||||||
|
|
||||||
quote! {
|
TokenStream::from(quote! {
|
||||||
#trai
|
#trai
|
||||||
|
|
||||||
impl #generics #name<State, WL, Tag> for WL {
|
impl<WL: WidgetLike<Tag>, Tag> #name<WL, Tag> for WL {
|
||||||
#(#impls)*
|
#(#impls)*
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[proc_macro_derive(UiState, attributes(rsc))]
|
|
||||||
pub fn derive_ui_state(input: TokenStream) -> TokenStream {
|
|
||||||
let mut output = proc_macro2::TokenStream::new();
|
|
||||||
|
|
||||||
let state: ItemStruct = parse_macro_input!(input);
|
|
||||||
let sname = state.ident;
|
|
||||||
let rscname = Ident::new(&(sname.to_string() + "Rsc"), sname.span());
|
|
||||||
let mut rsc_fields = Vec::new();
|
|
||||||
|
|
||||||
for field in state.fields {
|
|
||||||
let Some(attr) = field.attrs.iter().find(|a| a.path().is_ident("rsc")) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let Meta::List(list) = &attr.meta else {
|
|
||||||
output.extend(Error::new(attr.span(), "invalid attr syntax").into_compile_error());
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let tname: Ident = match list.parse_args::<Ident>() {
|
|
||||||
Ok(ident) => ident,
|
|
||||||
Err(err) => {
|
|
||||||
output.extend(err.to_compile_error());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let fty = &field.ty;
|
|
||||||
let fname = &field.ident.unwrap();
|
|
||||||
rsc_fields.extend(quote! {#fname: #fty,});
|
|
||||||
output.extend(quote! {
|
|
||||||
impl #tname for #sname {
|
|
||||||
fn get(&self) -> &#fty {
|
|
||||||
&self.#fname
|
|
||||||
}
|
|
||||||
fn get_mut(&mut self) -> &mut #fty {
|
|
||||||
&mut self.#fname
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl #tname for #rscname {
|
|
||||||
fn get(&self) -> &#fty {
|
|
||||||
&self.#fname
|
|
||||||
}
|
|
||||||
fn get_mut(&mut self) -> &mut #fty {
|
|
||||||
&mut self.#fname
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let vis = state.vis;
|
|
||||||
output.extend(quote! {
|
|
||||||
#vis struct #rscname {
|
|
||||||
#(#rsc_fields)*
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HasState for #sname {
|
|
||||||
type State = #sname;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HasState for #rscname {
|
|
||||||
type State = #sname;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StateLike<#sname> for #sname {
|
|
||||||
fn as_state(&mut self) -> &mut Self {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StateLike<#rscname> for #rscname {
|
|
||||||
fn as_state(&mut self) -> &mut Self {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
output.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[proc_macro_attribute]
|
|
||||||
pub fn default_ui_state(_attr: TokenStream, input: TokenStream) -> TokenStream {
|
|
||||||
let mut state: ItemStruct = parse_macro_input!(input);
|
|
||||||
let Fields::Named(fields) = &mut state.fields else {
|
|
||||||
panic!("must be on named fields struct");
|
|
||||||
};
|
|
||||||
let name = &state.ident;
|
|
||||||
state.attrs.push(parse_quote! {#[derive(UiState)]});
|
|
||||||
let new: FieldsNamed = parse_quote! {{
|
|
||||||
#[rsc(HasUi)]
|
|
||||||
pub ui: Ui,
|
|
||||||
#[rsc(HasDefaultUiState)]
|
|
||||||
pub ui_state: DefaultUiState,
|
|
||||||
#[rsc(HasEvents)]
|
|
||||||
pub events: iris::prelude::EventManager<#name>,
|
|
||||||
}};
|
|
||||||
fields.named.extend(new.named);
|
|
||||||
quote! {#state}.into()
|
|
||||||
}
|
}
|
||||||
|
|||||||
17
readme.md
17
readme.md
@@ -1,25 +1,22 @@
|
|||||||
# iris
|
# iris
|
||||||
|
|
||||||
My experimental attempt at a rust ui library (also my first ui library).
|
my fisrt attempt at a rust ui library
|
||||||
|
|
||||||
It's currently designed around using retained data structures (widgets), rather than diffing generated trees from data like xilem or iced. This is an experiment and I'm not sure if it's a good idea or not.
|
it's called iris because it's the structure around what you actually want to display and colorful
|
||||||
|
|
||||||
There's a `main.rs` that runs a testing window, so you can just `cargo run` to see it working.
|
there's a `main.rs` that runs a testing window, so can just `cargo run` to see it working
|
||||||
|
|
||||||
Goals, in general order:
|
goals, in general order:
|
||||||
1. does what I want it to (text, images, video, animations)
|
1. does what I want it to (text, images, video, animations)
|
||||||
2. very easy to use ignoring ergonomic ref counting
|
2. very easy to use ignoring ergonomic ref counting
|
||||||
3. reasonably fast / efficient (a lot faster than electron, save battery life)
|
3. reasonably fast / efficient (a lot faster than electron, save battery life)
|
||||||
|
|
||||||
## dev details
|
not targeting web rn cause wanna use actual nice gpu features & entire point of this is to make desktop apps
|
||||||
|
|
||||||
not targeting web rn cause wanna use actual nice gpu features & entire point of this is to make desktop apps / not need a web browser
|
|
||||||
|
|
||||||
general ideas trynna use rn / experiment with:
|
general ideas trynna use rn / experiment with:
|
||||||
- retained mode
|
- retained mode
|
||||||
- specifically designed around wgpu so there's no translation
|
- specifically designed around wgpu
|
||||||
- postfix functions for most things to prevent unreadable indentation (going very well)
|
- postfix functions for most things to prevent unreadable indentation (going very well)
|
||||||
- events can be done directly where you draw the widgets
|
|
||||||
- almost no macros in user code & actual LSP typechecking (variadic generics if you can hear me please save us)
|
- almost no macros in user code & actual LSP typechecking (variadic generics if you can hear me please save us)
|
||||||
- relative anchor + absolute offset coord system (+ "rest" / leftover during widget layout)
|
- relative anchor + absolute offset coord system (+ "rest" / leftover during widget layout)
|
||||||
- single threaded ui & pass context around to make non async usage straightforward (pretty unsure about this)
|
- single threaded ui & pass context around to make non async usage straightforward (pretty unsure about this)
|
||||||
@@ -27,5 +24,3 @@ general ideas trynna use rn / experiment with:
|
|||||||
|
|
||||||
under heavy initial development so not gonna try to explain status, maybe check TODO for that;
|
under heavy initial development so not gonna try to explain status, maybe check TODO for that;
|
||||||
sizable chance it gets a rewrite once I know everything I need and what seems to work best
|
sizable chance it gets a rewrite once I know everything I need and what seems to work best
|
||||||
|
|
||||||
it's called iris because it's the structure around what you actually want to display and colorful
|
|
||||||
|
|||||||
@@ -1,26 +1,20 @@
|
|||||||
use cosmic_text::Family;
|
use cosmic_text::Family;
|
||||||
use std::{cell::RefCell, rc::Rc};
|
use iris::prelude::*;
|
||||||
|
use len_fns::*;
|
||||||
use winit::event::WindowEvent;
|
use winit::event::WindowEvent;
|
||||||
|
|
||||||
iris::state_prelude!(ClientRsc);
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
App::<Client>::run();
|
DefaultApp::<Client>::run();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[default_ui_state]
|
|
||||||
pub struct Client {
|
pub struct Client {
|
||||||
info: WidgetRef<Text>,
|
info: WidgetRef<Text>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DefaultAppState for Client {
|
event_ctx!(Client);
|
||||||
fn new(ui_state: DefaultUiState, _proxy: Proxy<Self::Event>) -> Self {
|
|
||||||
let mut rsc = ClientRsc {
|
|
||||||
ui: Ui::new(),
|
|
||||||
ui_state,
|
|
||||||
events: EventManager::default(),
|
|
||||||
};
|
|
||||||
|
|
||||||
|
impl DefaultAppState for Client {
|
||||||
|
fn new(ui: &mut Ui, _state: &UiState, _proxy: 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),
|
||||||
@@ -43,7 +37,7 @@ impl DefaultAppState for Client {
|
|||||||
.width(rest(3)),
|
.width(rest(3)),
|
||||||
)
|
)
|
||||||
.span(Dir::RIGHT)
|
.span(Dir::RIGHT)
|
||||||
.add(&mut rsc);
|
.add(ui);
|
||||||
|
|
||||||
let span_test = (
|
let span_test = (
|
||||||
rrect.color(Color::GREEN).width(100),
|
rrect.color(Color::GREEN).width(100),
|
||||||
@@ -54,30 +48,31 @@ impl DefaultAppState for Client {
|
|||||||
rrect.color(Color::RED).width(100),
|
rrect.color(Color::RED).width(100),
|
||||||
)
|
)
|
||||||
.span(Dir::LEFT)
|
.span(Dir::LEFT)
|
||||||
.add(&mut rsc);
|
.add(ui);
|
||||||
|
|
||||||
let span_add = Span::empty(Dir::RIGHT).add(&mut rsc);
|
let span_add = Span::empty(Dir::RIGHT).add(ui);
|
||||||
|
let span_add_ = span_add.weak();
|
||||||
|
|
||||||
let add_button = rect(Color::LIME)
|
let add_button = rect(Color::LIME)
|
||||||
.radius(30)
|
.radius(30)
|
||||||
.on(CursorSense::click(), move |ctx| {
|
.on(CursorSense::click(), move |ctx| {
|
||||||
let child = image(include_bytes!("assets/sungals.png"))
|
let child = image(include_bytes!("assets/sungals.png"))
|
||||||
.center()
|
.center()
|
||||||
.add_strong(ctx);
|
.add(ctx.data.ui);
|
||||||
span_add(ctx).push(child);
|
span_add_.get_mut().children.push(child);
|
||||||
})
|
})
|
||||||
.sized((150, 150))
|
.sized((150, 150))
|
||||||
.align(Align::BOT_RIGHT);
|
.align(Align::BOT_RIGHT);
|
||||||
|
|
||||||
let del_button = rect(Color::RED)
|
let del_button = rect(Color::RED)
|
||||||
.radius(30)
|
.radius(30)
|
||||||
.on(CursorSense::click(), move |ctx| {
|
.on(CursorSense::click(), move |_| {
|
||||||
span_add(ctx).pop();
|
span_add_.get_mut().children.pop();
|
||||||
})
|
})
|
||||||
.sized((150, 150))
|
.sized((150, 150))
|
||||||
.align(Align::BOT_LEFT);
|
.align(Align::BOT_LEFT);
|
||||||
|
|
||||||
let span_add_test = (span_add, add_button, del_button).stack().add(&mut rsc);
|
let span_add_test = (span_add, add_button, del_button).stack().add(ui);
|
||||||
|
|
||||||
let btext = |content| wtext(content).size(30);
|
let btext = |content| wtext(content).size(30);
|
||||||
|
|
||||||
@@ -100,30 +95,31 @@ impl DefaultAppState for Client {
|
|||||||
wtext("pretty cool right?").size(50),
|
wtext("pretty cool right?").size(50),
|
||||||
)
|
)
|
||||||
.span(Dir::DOWN)
|
.span(Dir::DOWN)
|
||||||
.add(&mut rsc);
|
.add(ui);
|
||||||
|
|
||||||
let texts = Span::empty(Dir::DOWN).gap(10).add(&mut rsc);
|
let texts = Span::empty(Dir::DOWN).gap(10).add(ui);
|
||||||
let msg_area = texts.scrollable().masked().background(rect(Color::SKY));
|
let texts_ = texts.weak();
|
||||||
|
let msg_area = texts.scroll().masked().background(rect(Color::SKY));
|
||||||
let add_text = wtext("add")
|
let add_text = wtext("add")
|
||||||
.editable(EditMode::MultiLine)
|
.editable(false)
|
||||||
.text_align(Align::LEFT)
|
.text_align(Align::LEFT)
|
||||||
.size(30)
|
.size(30)
|
||||||
.attr::<Selectable>(())
|
.attr::<Selectable>(())
|
||||||
.on(Submit, move |ctx| {
|
.on(Submit, move |ctx| {
|
||||||
let w = ctx.widget;
|
let content = ctx.widget.get_mut().take();
|
||||||
let content = w.edit(ctx).take();
|
|
||||||
let text = wtext(content)
|
let text = wtext(content)
|
||||||
.editable(EditMode::MultiLine)
|
.editable(false)
|
||||||
.size(30)
|
.size(30)
|
||||||
.text_align(Align::LEFT)
|
.text_align(Align::LEFT)
|
||||||
.wrap(true)
|
.wrap(true)
|
||||||
.attr::<Selectable>(());
|
.attr::<Selectable>(());
|
||||||
let msg_box = text
|
let msg_box = text
|
||||||
.background(rect(Color::WHITE.darker(0.5)))
|
.background(rect(Color::WHITE.darker(0.5)))
|
||||||
.add_strong(ctx);
|
.add(&mut Ui::new());
|
||||||
texts(ctx).push(msg_box);
|
texts_.get_mut().children.push(msg_box);
|
||||||
})
|
})
|
||||||
.add(&mut rsc);
|
.add(ui);
|
||||||
|
let add_text_ = add_text.weak();
|
||||||
let text_edit_scroll = (
|
let text_edit_scroll = (
|
||||||
msg_area.height(rest(1)),
|
msg_area.height(rest(1)),
|
||||||
(
|
(
|
||||||
@@ -132,7 +128,7 @@ impl DefaultAppState for Client {
|
|||||||
add_text.width(rest(1)),
|
add_text.width(rest(1)),
|
||||||
Rect::new(Color::GREEN)
|
Rect::new(Color::GREEN)
|
||||||
.on(CursorSense::click(), move |ctx| {
|
.on(CursorSense::click(), move |ctx| {
|
||||||
ctx.state.run_event::<Submit>(add_text, &mut ());
|
Events::<Submit, _>::run(add_text_.id(), &mut (), ctx.state);
|
||||||
})
|
})
|
||||||
.sized((40, 40)),
|
.sized((40, 40)),
|
||||||
)
|
)
|
||||||
@@ -145,80 +141,73 @@ impl DefaultAppState for Client {
|
|||||||
.align(Align::BOT),
|
.align(Align::BOT),
|
||||||
)
|
)
|
||||||
.span(Dir::DOWN)
|
.span(Dir::DOWN)
|
||||||
.add(&mut rsc);
|
.add(ui);
|
||||||
|
|
||||||
let main = WidgetPtr::new().add(&mut rsc);
|
let main = pad_test.pad(10).add(ui);
|
||||||
|
let main_ = main.weak();
|
||||||
|
|
||||||
let vals = Rc::new(RefCell::new((0, Vec::new())));
|
let tab_handles = Handle::from((0, Vec::new()));
|
||||||
let mut switch_button = |color, to: WidgetRef, label| {
|
|
||||||
let to = to.upgrade(&mut rsc);
|
let switch_button = |color, to: Option<WidgetHandle>, label| {
|
||||||
let vec = &mut vals.borrow_mut().1;
|
let tab_handles = tab_handles.clone();
|
||||||
let i = vec.len();
|
let i = tab_handles.get().1.len();
|
||||||
if vec.is_empty() {
|
tab_handles.get_mut().1.push(to);
|
||||||
vec.push(None);
|
|
||||||
rsc.ui[main].set(to);
|
|
||||||
} else {
|
|
||||||
vec.push(Some(to));
|
|
||||||
}
|
|
||||||
let vals = vals.clone();
|
|
||||||
let rect = rect(color)
|
let rect = rect(color)
|
||||||
.on(CursorSense::click(), move |ctx| {
|
.on(CursorSense::click(), move |ctx| {
|
||||||
let (prev, vec) = &mut *vals.borrow_mut();
|
let (prev, all) = &mut *tab_handles.get_mut();
|
||||||
if let Some(h) = vec[i].take() {
|
if let Some(to) = &mut all[i] {
|
||||||
vec[*prev] = main(ctx).replace(h);
|
let mut main = main_.get_mut();
|
||||||
|
std::mem::swap(&mut main.inner, to);
|
||||||
|
all.swap(*prev, i);
|
||||||
*prev = i;
|
*prev = i;
|
||||||
}
|
}
|
||||||
ctx.widget().color = color.darker(0.3);
|
ctx.widget.get_mut().color = color.darker(0.3);
|
||||||
})
|
})
|
||||||
.on(
|
.on(
|
||||||
CursorSense::HoverStart | CursorSense::unclick(),
|
CursorSense::HoverStart | CursorSense::unclick(),
|
||||||
move |ctx| {
|
move |ctx| {
|
||||||
ctx.widget().color = color.brighter(0.2);
|
ctx.widget.get_mut().color = color.brighter(0.2);
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.on(CursorSense::HoverEnd, move |ctx| {
|
.on(CursorSense::HoverEnd, move |ctx| {
|
||||||
ctx.widget().color = color;
|
ctx.widget.get_mut().color = color;
|
||||||
});
|
});
|
||||||
(rect, wtext(label).size(30).text_align(Align::CENTER)).stack()
|
(rect, wtext(label).size(30).text_align(Align::CENTER)).stack()
|
||||||
};
|
};
|
||||||
|
|
||||||
let tabs = (
|
let tabs = (
|
||||||
switch_button(Color::RED, pad_test, "pad"),
|
switch_button(Color::RED, None, "pad"),
|
||||||
switch_button(Color::GREEN, span_test, "span"),
|
switch_button(Color::GREEN, Some(span_test), "span"),
|
||||||
switch_button(Color::BLUE, span_add_test, "image span"),
|
switch_button(Color::BLUE, Some(span_add_test), "image span"),
|
||||||
switch_button(Color::MAGENTA, text_test, "text layout"),
|
switch_button(Color::MAGENTA, Some(text_test), "text layout"),
|
||||||
switch_button(
|
switch_button(
|
||||||
Color::YELLOW.mul_rgb(0.5),
|
Color::YELLOW.mul_rgb(0.5),
|
||||||
text_edit_scroll,
|
Some(text_edit_scroll),
|
||||||
"text edit scroll",
|
"text edit scroll",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.span(Dir::RIGHT);
|
.span(Dir::RIGHT);
|
||||||
|
|
||||||
let info = wtext("").add(&mut rsc);
|
let info_ = wtext("").add(ui);
|
||||||
let info_sect = info.pad(10).align(Align::RIGHT);
|
let info = info_.weak();
|
||||||
|
let info_sect = info_.pad(10).align(Align::RIGHT);
|
||||||
|
|
||||||
((tabs.height(40), main.pad(10)).span(Dir::DOWN), info_sect)
|
((tabs.height(40), main).span(Dir::DOWN), info_sect)
|
||||||
.stack()
|
.stack()
|
||||||
.set_root(&mut rsc);
|
.set_root(ui);
|
||||||
|
|
||||||
Self {
|
Self { info }
|
||||||
ui: rsc.ui,
|
|
||||||
ui_state: rsc.ui_state,
|
|
||||||
events: rsc.events,
|
|
||||||
info,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn window_event(&mut self, _: WindowEvent) {
|
fn window_event(&mut self, _: WindowEvent, ui: &mut Ui, state: &UiState) {
|
||||||
let new = format!(
|
let new = format!(
|
||||||
"widgets: {}\nactive:{}\nviews: {}",
|
"widgets: {}\nactive:{}\nviews: {}",
|
||||||
self.ui.num_widgets(),
|
total_widgets(),
|
||||||
self.ui.active_widgets(),
|
ui.active_widgets(),
|
||||||
self.ui_state.renderer.ui.view_count()
|
state.renderer.ui.view_count()
|
||||||
);
|
);
|
||||||
if new != *self.ui[self.info].content {
|
if new != *self.info.get().content {
|
||||||
*self.ui[self.info].content = new;
|
*self.info.get_mut().content = new;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +1,38 @@
|
|||||||
use crate::prelude::*;
|
use crate::{default::UiState, prelude::*};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
use winit::dpi::{LogicalPosition, LogicalSize};
|
use winit::dpi::{LogicalPosition, LogicalSize};
|
||||||
|
|
||||||
|
event_ctx!(UiState);
|
||||||
|
|
||||||
pub struct Selector;
|
pub struct Selector;
|
||||||
|
|
||||||
impl<State: HasEvents, W: Widget + 'static> WidgetAttr<State, W> for Selector
|
impl<W: Widget + 'static> WidgetAttr<W> for Selector {
|
||||||
where
|
|
||||||
State::State: HasDefaultUiState,
|
|
||||||
{
|
|
||||||
type Input = WidgetRef<TextEdit>;
|
type Input = WidgetRef<TextEdit>;
|
||||||
|
|
||||||
fn run(state: &mut State, container: WidgetRef<W>, id: Self::Input) {
|
fn run(ui: &mut Ui, container: WidgetRef<W>, id: Self::Input) {
|
||||||
state.register_event(container, CursorSense::click_or_drag(), move |ctx| {
|
container.on(CursorSense::click_or_drag(), move |ctx| {
|
||||||
let region = ctx.ui().window_region(&id).unwrap();
|
let ui = &mut ctx.data.ui;
|
||||||
|
let region = 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 = ui.window_region(&container).unwrap().top_left;
|
||||||
let pos = ctx.data.pos + container_pos - id_pos;
|
let pos = ctx.data.pos + container_pos - id_pos;
|
||||||
let size = region.size();
|
let size = region.size();
|
||||||
select(ctx.state, id, pos, size, ctx.data.sense.is_dragging());
|
select(ui, id, ctx.state, pos, size, ctx.data.sense.is_dragging());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Selectable;
|
pub struct Selectable;
|
||||||
|
|
||||||
impl<State: HasEvents> WidgetAttr<State, TextEdit> for Selectable
|
impl WidgetAttr<TextEdit> for Selectable {
|
||||||
where
|
|
||||||
State::State: HasDefaultUiState,
|
|
||||||
{
|
|
||||||
type Input = ();
|
type Input = ();
|
||||||
|
|
||||||
fn run(state: &mut State, id: WidgetRef<TextEdit>, _: Self::Input) {
|
fn run(ui: &mut Ui, id: WidgetRef<TextEdit>, _: Self::Input) {
|
||||||
state.register_event(id, CursorSense::click_or_drag(), move |ctx| {
|
id.on(CursorSense::click_or_drag(), move |ctx| {
|
||||||
select(
|
select(
|
||||||
ctx.state,
|
ctx.data.ui,
|
||||||
id,
|
id,
|
||||||
|
ctx.state,
|
||||||
ctx.data.pos,
|
ctx.data.pos,
|
||||||
ctx.data.size,
|
ctx.data.size,
|
||||||
ctx.data.sense.is_dragging(),
|
ctx.data.sense.is_dragging(),
|
||||||
@@ -44,17 +42,17 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn select(
|
fn select(
|
||||||
state: &mut impl HasDefaultUiState,
|
ui: &mut Ui,
|
||||||
id: WidgetRef<TextEdit>,
|
id: WidgetRef<TextEdit>,
|
||||||
|
state: &mut UiState,
|
||||||
pos: Vec2,
|
pos: Vec2,
|
||||||
size: Vec2,
|
size: Vec2,
|
||||||
dragging: bool,
|
dragging: bool,
|
||||||
) {
|
) {
|
||||||
let (ui, state) = HasDefaultUiState::ui_with_state(state);
|
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
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(ui).select(pos, size, dragging, recent);
|
id.get_mut().select(pos, size, dragging, recent);
|
||||||
if let Some(region) = ui.window_region(&id) {
|
if let Some(region) = ui.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(
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
use iris_core::Event;
|
use iris_core::layout::Event;
|
||||||
|
|
||||||
#[derive(Eq, PartialEq, Hash, Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Submit;
|
pub struct Submit;
|
||||||
impl Event for Submit {}
|
impl Event for Submit {}
|
||||||
|
|
||||||
#[derive(Eq, PartialEq, Hash, Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Edited;
|
pub struct Edited;
|
||||||
impl Event for Edited {}
|
impl Event for Edited {}
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
use crate::prelude::*;
|
use crate::{
|
||||||
|
widget::{CursorState, Modifiers},
|
||||||
|
layout::Vec2,
|
||||||
|
default::UiState,
|
||||||
|
};
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{MouseButton, MouseScrollDelta, WindowEvent},
|
event::{MouseButton, MouseScrollDelta, WindowEvent},
|
||||||
keyboard::{Key, NamedKey},
|
keyboard::{Key, NamedKey},
|
||||||
@@ -66,7 +70,7 @@ impl Input {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DefaultUiState {
|
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()
|
||||||
|
|||||||
@@ -1,30 +1,33 @@
|
|||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use arboard::Clipboard;
|
use arboard::Clipboard;
|
||||||
use iris_core::util::forget_mut;
|
use std::sync::Arc;
|
||||||
use std::{marker::Sized, sync::Arc, time::Instant};
|
use std::time::Instant;
|
||||||
use winit::{
|
use winit::event::{Ime, WindowEvent};
|
||||||
event::{Ime, WindowEvent},
|
use winit::event_loop::{ActiveEventLoop, EventLoopProxy};
|
||||||
event_loop::{ActiveEventLoop, EventLoopProxy},
|
use winit::window::{Window, WindowAttributes};
|
||||||
window::{Window, WindowAttributes},
|
|
||||||
};
|
|
||||||
|
|
||||||
mod app;
|
mod app;
|
||||||
mod attr;
|
mod attr;
|
||||||
mod event;
|
mod event;
|
||||||
mod input;
|
mod input;
|
||||||
mod render;
|
mod render;
|
||||||
mod sense;
|
|
||||||
|
|
||||||
pub use app::*;
|
pub use app::*;
|
||||||
pub use attr::*;
|
pub use attr::*;
|
||||||
pub use event::*;
|
pub use event::*;
|
||||||
pub use input::*;
|
pub use input::*;
|
||||||
pub use render::*;
|
pub use render::*;
|
||||||
pub use sense::*;
|
|
||||||
|
|
||||||
pub type Proxy<Event> = EventLoopProxy<Event>;
|
pub type Proxy<Event> = EventLoopProxy<Event>;
|
||||||
|
pub type DefaultApp<Data> = App<DefaultState<Data>>;
|
||||||
|
|
||||||
pub struct DefaultUiState {
|
pub struct DefaultState<AppState> {
|
||||||
|
ui: Ui,
|
||||||
|
ui_state: UiState,
|
||||||
|
app_state: AppState,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct UiState {
|
||||||
pub renderer: UiRenderer,
|
pub renderer: UiRenderer,
|
||||||
pub input: Input,
|
pub input: Input,
|
||||||
pub focus: Option<WidgetRef<TextEdit>>,
|
pub focus: Option<WidgetRef<TextEdit>>,
|
||||||
@@ -34,10 +37,31 @@ pub struct DefaultUiState {
|
|||||||
pub last_click: Instant,
|
pub last_click: Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DefaultUiState {
|
pub trait DefaultAppState: 'static {
|
||||||
pub fn new(window: impl Into<Arc<Window>>) -> Self {
|
type Event: 'static = ();
|
||||||
let window = window.into();
|
fn new(ui: &mut Ui, state: &UiState, proxy: Proxy<Self::Event>) -> Self;
|
||||||
Self {
|
#[allow(unused_variables)]
|
||||||
|
fn event(&mut self, event: Self::Event, ui: &mut Ui, state: &UiState) {}
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
fn exit(&mut self, ui: &mut Ui, state: &UiState) {}
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
fn window_event(&mut self, event: WindowEvent, ui: &mut Ui, state: &UiState) {}
|
||||||
|
fn window_attrs() -> WindowAttributes {
|
||||||
|
WindowAttributes::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<State: DefaultAppState> AppState for DefaultState<State> {
|
||||||
|
type Event = State::Event;
|
||||||
|
|
||||||
|
fn new(event_loop: &ActiveEventLoop, proxy: EventLoopProxy<Self::Event>) -> Self {
|
||||||
|
let window = Arc::new(
|
||||||
|
event_loop
|
||||||
|
.create_window(State::window_attrs())
|
||||||
|
.expect("failed to create window "),
|
||||||
|
);
|
||||||
|
let mut ui = Ui::new();
|
||||||
|
let ui_state = UiState {
|
||||||
renderer: UiRenderer::new(window.clone()),
|
renderer: UiRenderer::new(window.clone()),
|
||||||
window,
|
window,
|
||||||
input: Input::default(),
|
input: Input::default(),
|
||||||
@@ -45,57 +69,26 @@ impl DefaultUiState {
|
|||||||
ime: 0,
|
ime: 0,
|
||||||
last_click: Instant::now(),
|
last_click: Instant::now(),
|
||||||
focus: None,
|
focus: None,
|
||||||
|
};
|
||||||
|
let app_state = State::new(&mut ui, &ui_state, proxy);
|
||||||
|
Self {
|
||||||
|
ui,
|
||||||
|
ui_state,
|
||||||
|
app_state,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
pub trait HasDefaultUiState: Sized + 'static + HasUi {
|
|
||||||
fn get(&self) -> &DefaultUiState;
|
|
||||||
fn get_mut(&mut self) -> &mut DefaultUiState;
|
|
||||||
fn ui_state(&self) -> &DefaultUiState {
|
|
||||||
HasDefaultUiState::get(self)
|
|
||||||
}
|
|
||||||
fn ui_state_mut(&mut self) -> &mut DefaultUiState {
|
|
||||||
HasDefaultUiState::get_mut(self)
|
|
||||||
}
|
|
||||||
fn ui_with_state(&mut self) -> (&mut Ui, &mut DefaultUiState) {
|
|
||||||
// as long as you're not doing anything actually unhinged this should always work safely
|
|
||||||
(
|
|
||||||
unsafe { forget_mut(self.ui_mut()) },
|
|
||||||
HasDefaultUiState::get_mut(self),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait DefaultAppState: RunEvents + HasDefaultUiState {
|
|
||||||
type Event: 'static = ();
|
|
||||||
fn new(ui_state: DefaultUiState, proxy: Proxy<Self::Event>) -> Self;
|
|
||||||
#[allow(unused_variables)]
|
|
||||||
fn event(&mut self, event: Self::Event) {}
|
|
||||||
#[allow(unused_variables)]
|
|
||||||
fn exit(&mut self) {}
|
|
||||||
#[allow(unused_variables)]
|
|
||||||
fn window_event(&mut self, event: WindowEvent) {}
|
|
||||||
fn window_attributes() -> WindowAttributes {
|
|
||||||
Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<State: DefaultAppState> AppState for State {
|
|
||||||
type Event = State::Event;
|
|
||||||
|
|
||||||
fn new(event_loop: &ActiveEventLoop, proxy: EventLoopProxy<Self::Event>) -> Self {
|
|
||||||
let window = event_loop.create_window(Self::window_attributes()).unwrap();
|
|
||||||
Self::new(DefaultUiState::new(window), proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn event(&mut self, event: Self::Event, _: &ActiveEventLoop) {
|
fn event(&mut self, event: Self::Event, _: &ActiveEventLoop) {
|
||||||
self.event(event);
|
self.app_state.event(event, &mut self.ui, &self.ui_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_mut()) };
|
let Self {
|
||||||
let ui_state = HasDefaultUiState::get_mut(self);
|
ui,
|
||||||
|
ui_state,
|
||||||
|
app_state,
|
||||||
|
} = self;
|
||||||
|
|
||||||
let input_changed = ui_state.input.event(&event);
|
let input_changed = ui_state.input.event(&event);
|
||||||
let cursor_state = ui_state.cursor_state().clone();
|
let cursor_state = ui_state.cursor_state().clone();
|
||||||
let old = ui_state.focus;
|
let old = ui_state.focus;
|
||||||
@@ -104,18 +97,21 @@ impl<State: DefaultAppState> AppState for State {
|
|||||||
}
|
}
|
||||||
if input_changed {
|
if input_changed {
|
||||||
let window_size = ui_state.window_size();
|
let window_size = ui_state.window_size();
|
||||||
self.run_sensors(&cursor_state, window_size);
|
// call sensors with all 3 important contexts
|
||||||
|
// TODO: allow user to specify custom contexts?
|
||||||
|
// and give them both states in case they need both
|
||||||
|
ui.run_sensors(&mut (), &cursor_state, window_size);
|
||||||
|
ui.run_sensors(ui_state, &cursor_state, window_size);
|
||||||
|
ui.run_sensors(app_state, &cursor_state, window_size);
|
||||||
}
|
}
|
||||||
let (mut ui, mut ui_state) = self.ui_with_state();
|
|
||||||
if old != ui_state.focus
|
if old != ui_state.focus
|
||||||
&& let Some(old) = old
|
&& let Some(old) = old
|
||||||
{
|
{
|
||||||
old.edit(ui).deselect();
|
old.get_mut().deselect();
|
||||||
}
|
}
|
||||||
match &event {
|
match &event {
|
||||||
WindowEvent::CloseRequested => event_loop.exit(),
|
WindowEvent::CloseRequested => event_loop.exit(),
|
||||||
WindowEvent::RedrawRequested => {
|
WindowEvent::RedrawRequested => {
|
||||||
ui.update(events);
|
|
||||||
ui_state.renderer.update(ui);
|
ui_state.renderer.update(ui);
|
||||||
ui_state.renderer.draw();
|
ui_state.renderer.draw();
|
||||||
}
|
}
|
||||||
@@ -127,20 +123,20 @@ impl<State: DefaultAppState> AppState for State {
|
|||||||
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 res = sel.get_mut().apply_event(event, &ui_state.input.modifiers);
|
||||||
match text.apply_event(event, &ui_state.input.modifiers) {
|
match res {
|
||||||
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.run_event::<Submit>(sel, &mut ());
|
Events::<Submit, _>::run(sel.id(), &mut (), app_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);
|
sel.get_mut().insert(&t);
|
||||||
}
|
}
|
||||||
self.run_event::<Edited>(sel, &mut ());
|
Events::<Edited, _>::run(sel.id(), &mut (), app_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) {
|
||||||
@@ -148,39 +144,37 @@ impl<State: DefaultAppState> AppState for State {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
TextInputResult::Used => {
|
TextInputResult::Used => {
|
||||||
self.run_event::<Edited>(sel, &mut ());
|
Events::<Edited, _>::run(sel.id(), &mut (), app_state);
|
||||||
}
|
}
|
||||||
TextInputResult::Unused => {}
|
TextInputResult::Unused => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
WindowEvent::Ime(ime) => {
|
WindowEvent::Ime(ime) => {
|
||||||
if let Some(sel) = ui_state.focus {
|
if let Some(sel) = &ui_state.focus {
|
||||||
let mut text = sel.edit(ui);
|
|
||||||
match ime {
|
match ime {
|
||||||
Ime::Enabled | Ime::Disabled => (),
|
Ime::Enabled | Ime::Disabled => (),
|
||||||
Ime::Preedit(content, _pos) => {
|
Ime::Preedit(content, _pos) => {
|
||||||
// TODO: highlight once that's real
|
// TODO: highlight once that's real
|
||||||
text.replace(ui_state.ime, content);
|
sel.get_mut().replace(ui_state.ime, content);
|
||||||
ui_state.ime = content.chars().count();
|
ui_state.ime = content.chars().count();
|
||||||
}
|
}
|
||||||
Ime::Commit(content) => {
|
Ime::Commit(content) => {
|
||||||
text.insert(content);
|
sel.get_mut().insert(content);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
self.window_event(event);
|
app_state.window_event(event, ui, ui_state);
|
||||||
(ui, ui_state) = self.ui_with_state();
|
if ui.update() {
|
||||||
if ui.needs_redraw() {
|
|
||||||
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.exit();
|
self.app_state.exit(&mut self.ui, &self.ui_state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
use iris_core::{Ui, UiLimits, UiRenderNode};
|
use crate::{
|
||||||
|
layout::Ui,
|
||||||
|
render::{UiLimits, UiRenderNode},
|
||||||
|
};
|
||||||
use pollster::FutureExt;
|
use pollster::FutureExt;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use wgpu::{util::StagingBelt, *};
|
use wgpu::{util::StagingBelt, *};
|
||||||
@@ -18,8 +21,8 @@ pub struct UiRenderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl UiRenderer {
|
impl UiRenderer {
|
||||||
pub fn update(&mut self, ui: &mut Ui) {
|
pub fn update(&mut self, updates: &mut Ui) {
|
||||||
self.ui.update(&self.device, &self.queue, ui);
|
self.ui.update(&self.device, &self.queue, updates);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn draw(&mut self) {
|
pub fn draw(&mut self) {
|
||||||
@@ -69,6 +72,7 @@ impl UiRenderer {
|
|||||||
|
|
||||||
let instance = Instance::new(&InstanceDescriptor {
|
let instance = Instance::new(&InstanceDescriptor {
|
||||||
backends: Backends::PRIMARY,
|
backends: Backends::PRIMARY,
|
||||||
|
flags: InstanceFlags::empty(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -118,7 +122,7 @@ impl UiRenderer {
|
|||||||
format: surface_format,
|
format: surface_format,
|
||||||
width: size.width,
|
width: size.width,
|
||||||
height: size.height,
|
height: size.height,
|
||||||
present_mode: PresentMode::AutoNoVsync,
|
present_mode: PresentMode::AutoVsync,
|
||||||
alpha_mode: surface_caps.alpha_modes[0],
|
alpha_mode: surface_caps.alpha_modes[0],
|
||||||
desired_maximum_frame_latency: 2,
|
desired_maximum_frame_latency: 2,
|
||||||
view_formats: vec![],
|
view_formats: vec![],
|
||||||
|
|||||||
67
src/event.rs
67
src/event.rs
@@ -1,25 +1,66 @@
|
|||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
|
use iris_macro::widget_trait;
|
||||||
|
|
||||||
pub mod eventable {
|
pub mod eventable {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
widget_trait! {
|
widget_trait! {
|
||||||
pub trait Eventable<State: HasEvents + StateLike<State> + 'static>;
|
pub trait Eventable;
|
||||||
fn on<E: EventLike>(
|
fn on<E: EventAlias, Ctx: 'static>(
|
||||||
self,
|
self,
|
||||||
event: E,
|
event: E,
|
||||||
f: impl for<'a> WidgetEventFn<State::State, <E::Event as Event>::Data<'a>, WL::Widget>,
|
f: impl for<'a> EventIdFn<Ctx, <E::Event as Event>::Data<'a>, WL::Widget>,
|
||||||
) -> impl WidgetIdFn<State, WL::Widget> {
|
) -> impl WidgetIdFn<WL::Widget> {
|
||||||
move |state| {
|
move |ui| {
|
||||||
let id = self.add(state);
|
let id = self.add(ui);
|
||||||
state.register_event(id, event.into_event(), move |ctx| {
|
Events::<E::Event, Ctx>::register(id.weak(), event.into_event(), f);
|
||||||
f(&mut EventIdCtx {
|
|
||||||
widget: id,
|
|
||||||
state: ctx.state,
|
|
||||||
data: ctx.data,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
id
|
id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: naming in here is a bit weird like eventable
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! event_ctx {
|
||||||
|
($ty: ty) => {
|
||||||
|
mod local_event_trait {
|
||||||
|
use super::*;
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
use $crate::prelude::*;
|
||||||
|
|
||||||
|
widget_trait! {
|
||||||
|
#[allow(unused)]
|
||||||
|
pub trait EventableCtx;
|
||||||
|
fn on<E: EventAlias>(
|
||||||
|
self,
|
||||||
|
event: E,
|
||||||
|
f: impl for<'a> EventIdFn<$ty, <E::Event as Event>::Data<'a>, WL::Widget>,
|
||||||
|
) -> impl WidgetIdFn<WL::Widget> {
|
||||||
|
eventable::Eventable::on(self, event, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
use std::marker::Sized;
|
||||||
|
#[allow(unused)]
|
||||||
|
pub trait EventableCtxRef<W: Widget + ?Sized> {
|
||||||
|
fn on<E: EventAlias>(
|
||||||
|
self,
|
||||||
|
event: E,
|
||||||
|
f: impl for<'a> EventIdFn<$ty, <E::Event as Event>::Data<'a>, W>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Widget + ?Sized> EventableCtxRef<W> for WidgetRef<W> {
|
||||||
|
fn on<E: EventAlias>(
|
||||||
|
self,
|
||||||
|
event: E,
|
||||||
|
f: impl for<'a> EventIdFn<$ty, <E::Event as Event>::Data<'a>, W>,
|
||||||
|
) {
|
||||||
|
Events::<E::Event, $ty>::register(self, event.into_event(), f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
use local_event_trait::*;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
pub use event_ctx;
|
||||||
|
|||||||
41
src/lib.rs
41
src/lib.rs
@@ -2,37 +2,22 @@
|
|||||||
#![feature(fn_traits)]
|
#![feature(fn_traits)]
|
||||||
#![feature(gen_blocks)]
|
#![feature(gen_blocks)]
|
||||||
#![feature(associated_type_defaults)]
|
#![feature(associated_type_defaults)]
|
||||||
#![feature(unsize)]
|
|
||||||
|
|
||||||
pub mod default;
|
mod default;
|
||||||
pub mod event;
|
mod event;
|
||||||
pub mod typed;
|
mod widget;
|
||||||
pub mod widget;
|
|
||||||
|
|
||||||
pub use iris_core as core;
|
|
||||||
pub use iris_macro as macros;
|
|
||||||
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! state_prelude {
|
|
||||||
($vis:vis $state:ty) => {
|
|
||||||
iris::event_state!($vis $state);
|
|
||||||
$vis use iris::{
|
|
||||||
default::*,
|
|
||||||
core::{len_fns::*, util::Vec2, *},
|
|
||||||
macros::*,
|
|
||||||
widget::*,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub mod prelude {
|
|
||||||
use super::*;
|
|
||||||
pub use default::*;
|
|
||||||
pub use event::*;
|
|
||||||
pub use iris_core::*;
|
pub use iris_core::*;
|
||||||
pub use iris_macro::*;
|
pub use iris_macro::*;
|
||||||
pub use widget::*;
|
|
||||||
|
|
||||||
pub use iris_core::util::Vec2;
|
pub mod prelude {
|
||||||
pub use typed::*;
|
pub use super::default::*;
|
||||||
|
pub use super::event::*;
|
||||||
|
pub use super::widget::*;
|
||||||
|
|
||||||
|
pub use iris_core::layout::*;
|
||||||
|
pub use iris_core::render::*;
|
||||||
|
pub use iris_core::util::Handle;
|
||||||
|
|
||||||
|
pub use iris_macro::*;
|
||||||
}
|
}
|
||||||
|
|||||||
37
src/typed.rs
37
src/typed.rs
@@ -1,37 +0,0 @@
|
|||||||
#[macro_export]
|
|
||||||
macro_rules! event_state {
|
|
||||||
($vis:vis $state:ty) => {
|
|
||||||
mod local_event_trait {
|
|
||||||
use super::*;
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
use $crate::prelude::*;
|
|
||||||
pub trait EventableCtx<WL: WidgetLike<$state, Tag>, Tag> {
|
|
||||||
fn on<E: EventLike>(
|
|
||||||
self,
|
|
||||||
event: E,
|
|
||||||
f: impl for<'a> WidgetEventFn<
|
|
||||||
<$state as HasState>::State,
|
|
||||||
<E::Event as Event>::Data<'a>,
|
|
||||||
WL::Widget
|
|
||||||
>,
|
|
||||||
) -> impl WidgetIdFn<$state, WL::Widget>;
|
|
||||||
}
|
|
||||||
impl<WL: WidgetLike<$state, Tag>, Tag> EventableCtx<WL, Tag> for WL {
|
|
||||||
fn on<E: EventLike>(
|
|
||||||
self,
|
|
||||||
event: E,
|
|
||||||
f: impl for<'a> WidgetEventFn<
|
|
||||||
<$state as HasState>::State,
|
|
||||||
<E::Event as Event>::Data<'a>,
|
|
||||||
WL::Widget
|
|
||||||
>,
|
|
||||||
) -> impl WidgetIdFn<$state, WL::Widget> {
|
|
||||||
eventable::Eventable::on(self, event, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$vis type EventManager = $crate::prelude::EventManager<<$state as HasState>::State>;
|
|
||||||
$vis use local_event_trait::*;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
pub use event_state;
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::prelude::*;
|
|
||||||
use image::DynamicImage;
|
use image::DynamicImage;
|
||||||
|
use crate::prelude::*;
|
||||||
|
|
||||||
pub struct Image {
|
pub struct Image {
|
||||||
handle: TextureHandle,
|
handle: TextureHandle,
|
||||||
@@ -19,10 +19,10 @@ impl Widget for Image {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn image<State: HasUi>(image: impl LoadableImage) -> impl WidgetFn<State, Image> {
|
pub fn image(image: impl LoadableImage) -> impl WidgetFn<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 |ui| Image {
|
||||||
handle: state.get_mut().add_texture(image),
|
handle: ui.add_texture(image),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ mod mask;
|
|||||||
mod position;
|
mod position;
|
||||||
mod ptr;
|
mod ptr;
|
||||||
mod rect;
|
mod rect;
|
||||||
|
mod sense;
|
||||||
mod text;
|
mod text;
|
||||||
mod trait_fns;
|
mod trait_fns;
|
||||||
|
|
||||||
@@ -11,5 +12,6 @@ pub use mask::*;
|
|||||||
pub use position::*;
|
pub use position::*;
|
||||||
pub use ptr::*;
|
pub use ptr::*;
|
||||||
pub use rect::*;
|
pub use rect::*;
|
||||||
|
pub use sense::*;
|
||||||
pub use text::*;
|
pub use text::*;
|
||||||
pub use trait_fns::*;
|
pub use trait_fns::*;
|
||||||
|
|||||||
@@ -62,14 +62,6 @@ impl Span {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn push(&mut self, w: WidgetHandle) {
|
|
||||||
self.children.push(w);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pop(&mut self) -> Option<WidgetHandle> {
|
|
||||||
self.children.pop()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn len_sum(&mut self, ctx: &mut SizeCtx) -> 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| {
|
||||||
@@ -152,31 +144,28 @@ impl Span {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct SpanBuilder<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> {
|
pub struct SpanBuilder<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> {
|
||||||
pub children: Wa,
|
pub children: Wa,
|
||||||
pub dir: Dir,
|
pub dir: Dir,
|
||||||
pub gap: f32,
|
pub gap: f32,
|
||||||
_pd: PhantomData<(State, Tag)>,
|
_pd: PhantomData<Tag>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State: StateLike<State>, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
|
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)>
|
||||||
WidgetFnTrait<State> for SpanBuilder<State, LEN, Wa, Tag>
|
for SpanBuilder<LEN, Wa, Tag>
|
||||||
{
|
{
|
||||||
type Widget = Span;
|
type Output = Span;
|
||||||
|
|
||||||
#[track_caller]
|
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output {
|
||||||
fn run(self, state: &mut State) -> Self::Widget {
|
|
||||||
Span {
|
Span {
|
||||||
children: self.children.add(state).arr.into_iter().collect(),
|
children: self.children.ui(args.0).arr.into_iter().collect(),
|
||||||
dir: self.dir,
|
dir: self.dir,
|
||||||
gap: self.gap,
|
gap: self.gap,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
|
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> SpanBuilder<LEN, Wa, Tag> {
|
||||||
SpanBuilder<State, LEN, Wa, Tag>
|
|
||||||
{
|
|
||||||
pub fn new(children: Wa, dir: Dir) -> Self {
|
pub fn new(children: Wa, dir: Dir) -> Self {
|
||||||
Self {
|
Self {
|
||||||
children,
|
children,
|
||||||
|
|||||||
@@ -42,28 +42,26 @@ pub enum StackSize {
|
|||||||
Child(usize),
|
Child(usize),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct StackBuilder<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> {
|
pub struct StackBuilder<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> {
|
||||||
pub children: Wa,
|
pub children: Wa,
|
||||||
pub size: StackSize,
|
pub size: StackSize,
|
||||||
_pd: PhantomData<(State, Tag)>,
|
_pd: PhantomData<Tag>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State: StateLike<State>, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> FnOnce<(&mut State,)>
|
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> FnOnce<(&mut Ui,)>
|
||||||
for StackBuilder<State, LEN, Wa, Tag>
|
for StackBuilder<LEN, Wa, Tag>
|
||||||
{
|
{
|
||||||
type Output = Stack;
|
type Output = Stack;
|
||||||
|
|
||||||
extern "rust-call" fn call_once(self, args: (&mut State,)) -> Self::Output {
|
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output {
|
||||||
Stack {
|
Stack {
|
||||||
children: self.children.add(args.0).arr.into_iter().collect(),
|
children: self.children.ui(args.0).arr.into_iter().collect(),
|
||||||
size: self.size,
|
size: self.size,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
|
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> StackBuilder<LEN, Wa, Tag> {
|
||||||
StackBuilder<State, LEN, Wa, Tag>
|
|
||||||
{
|
|
||||||
pub fn new(children: Wa) -> Self {
|
pub fn new(children: Wa) -> Self {
|
||||||
Self {
|
Self {
|
||||||
children,
|
children,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use std::marker::{Sized, Unsize};
|
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
pub struct WidgetPtr {
|
pub struct WidgetPtr {
|
||||||
pub inner: Option<WidgetHandle>,
|
pub inner: Option<WidgetHandle>,
|
||||||
}
|
}
|
||||||
@@ -28,30 +28,3 @@ impl Widget for WidgetPtr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WidgetPtr {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
pub fn empty() -> Self {
|
|
||||||
Self {
|
|
||||||
inner: Default::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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for WidgetPtr {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::empty()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::layout::{UiRegion, Vec2};
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use std::{
|
use std::{
|
||||||
ops::{BitOr, Deref, DerefMut},
|
ops::{BitOr, Deref, DerefMut},
|
||||||
@@ -134,26 +135,33 @@ pub struct CursorData<'a> {
|
|||||||
pub scroll_delta: Vec2,
|
pub scroll_delta: Vec2,
|
||||||
pub hover: ActivationState,
|
pub hover: ActivationState,
|
||||||
pub cursor: &'a CursorState,
|
pub cursor: &'a CursorState,
|
||||||
|
pub ui: &'a mut Ui,
|
||||||
/// the first sense that triggered this
|
/// the first sense that triggered this
|
||||||
pub sense: CursorSense,
|
pub sense: CursorSense,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait SensorUi<State> {
|
pub trait SensorUi {
|
||||||
fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2);
|
fn run_sensors<Ctx: 'static>(&mut self, ctx: &mut Ctx, cursor: &CursorState, window_size: Vec2);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State: RunEvents> SensorUi<State> for State {
|
impl SensorUi for Ui {
|
||||||
fn run_sensors(&mut self, cursor: &CursorState, window_size: Vec2) {
|
fn run_sensors<Ctx: 'static>(
|
||||||
let layers = std::mem::take(&mut self.ui_mut().layers);
|
&mut self,
|
||||||
let mut active = std::mem::take(&mut self.events_mut().get_type::<CursorSense>().active);
|
ctx: &mut Ctx,
|
||||||
for layer in layers.indices().rev() {
|
cursor: &CursorState,
|
||||||
|
window_size: Vec2,
|
||||||
|
) {
|
||||||
|
let ui_id = self.id();
|
||||||
|
let layers = std::mem::take(&mut self.data_mut().layers);
|
||||||
|
let mut active = std::mem::take(&mut *Events::<CursorSenses, Ctx>::active(ui_id));
|
||||||
|
for i 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, state) in active.get_mut(&i).into_iter().flatten() {
|
||||||
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);
|
state.hover.update(in_shape);
|
||||||
if sensor.hover == ActivationState::Off {
|
if state.hover == ActivationState::Off {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
sensed = true;
|
sensed = true;
|
||||||
@@ -162,20 +170,22 @@ impl<State: RunEvents> SensorUi<State> for State {
|
|||||||
pos: cursor.pos - region.top_left,
|
pos: cursor.pos - region.top_left,
|
||||||
size: region.bot_right - region.top_left,
|
size: region.bot_right - region.top_left,
|
||||||
scroll_delta: cursor.scroll_delta,
|
scroll_delta: cursor.scroll_delta,
|
||||||
hover: sensor.hover,
|
hover: state.hover,
|
||||||
cursor,
|
cursor,
|
||||||
|
ui: self,
|
||||||
// this does not have any meaning;
|
// this does not have any meaning;
|
||||||
// might wanna set up Event to have a prepare stage
|
// might wanna set up Event to have a prepare stage
|
||||||
sense: CursorSense::Hovering,
|
sense: CursorSense::Hovering,
|
||||||
};
|
};
|
||||||
self.run_event::<CursorSense>(*id, &mut data);
|
Events::<CursorSenses, Ctx>::run(*id, &mut data, ctx);
|
||||||
}
|
}
|
||||||
if sensed {
|
if sensed {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.events_mut().get_type::<CursorSense>().active = active;
|
|
||||||
self.ui_mut().layers = layers;
|
*Events::<CursorSenses, Ctx>::active(ui_id) = active;
|
||||||
|
self.data_mut().layers = layers;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,10 +253,10 @@ impl ActivationState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLike for CursorSense {
|
impl EventAlias for CursorSense {
|
||||||
type Event = CursorSenses;
|
type Event = CursorSenses;
|
||||||
fn into_event(self) -> Self::Event {
|
fn into_event(self) -> Self::Event {
|
||||||
self.into()
|
CursorSenses::from(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,16 +1,15 @@
|
|||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use cosmic_text::{Attrs, Family, Metrics};
|
use cosmic_text::{Attrs, Family, Metrics};
|
||||||
use std::marker::{PhantomData, Sized};
|
use std::marker::Sized;
|
||||||
|
|
||||||
pub struct TextBuilder<State, O = TextOutput, H: WidgetOption<State> = ()> {
|
pub struct TextBuilder<O = TextOutput, H: WidgetOption = ()> {
|
||||||
pub content: String,
|
pub content: String,
|
||||||
pub attrs: TextAttrs,
|
pub attrs: TextAttrs,
|
||||||
pub hint: H,
|
pub hint: H,
|
||||||
pub output: O,
|
pub output: O,
|
||||||
state: PhantomData<State>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State, O, H: WidgetOption<State>> TextBuilder<State, O, H> {
|
impl<O, H: WidgetOption> TextBuilder<O, H> {
|
||||||
pub fn size(mut self, size: impl UiNum) -> Self {
|
pub fn size(mut self, size: impl UiNum) -> Self {
|
||||||
self.attrs.font_size = size.to_f32();
|
self.attrs.font_size = size.to_f32();
|
||||||
self.attrs.line_height = self.attrs.font_size * LINE_HEIGHT_MULT;
|
self.attrs.line_height = self.attrs.font_size * LINE_HEIGHT_MULT;
|
||||||
@@ -40,54 +39,43 @@ impl<State, O, H: WidgetOption<State>> TextBuilder<State, O, H> {
|
|||||||
self.attrs.wrap = wrap;
|
self.attrs.wrap = wrap;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
pub fn editable(self, mode: EditMode) -> TextBuilder<State, TextEditOutput, H> {
|
pub fn editable(self, single_line: bool) -> TextBuilder<TextEditOutput, H> {
|
||||||
TextBuilder {
|
TextBuilder {
|
||||||
content: self.content,
|
content: self.content,
|
||||||
attrs: self.attrs,
|
attrs: self.attrs,
|
||||||
hint: self.hint,
|
hint: self.hint,
|
||||||
output: TextEditOutput { mode },
|
output: TextEditOutput { single_line },
|
||||||
state: PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State: HasUi + StateLike<State>, O> TextBuilder<State, O> {
|
impl<O> TextBuilder<O> {
|
||||||
pub fn hint<W: WidgetLike<State, Tag>, Tag>(
|
pub fn hint<W: WidgetLike<Tag>, Tag>(self, hint: W) -> TextBuilder<O, impl WidgetOption> {
|
||||||
self,
|
|
||||||
hint: W,
|
|
||||||
) -> TextBuilder<State, O, impl WidgetOption<State>> {
|
|
||||||
TextBuilder {
|
TextBuilder {
|
||||||
content: self.content,
|
content: self.content,
|
||||||
attrs: self.attrs,
|
attrs: self.attrs,
|
||||||
hint: move |ui: &mut State| Some(hint.add_strong(ui).any()),
|
hint: move |ui: &mut Ui| Some(hint.add(ui).any()),
|
||||||
output: self.output,
|
output: self.output,
|
||||||
state: PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait TextBuilderOutput<State>: Sized {
|
pub trait TextBuilderOutput: Sized {
|
||||||
type Output;
|
type Output;
|
||||||
fn run<H: WidgetOption<State>>(
|
fn run<H: WidgetOption>(ui: &mut Ui, builder: TextBuilder<Self, H>) -> Self::Output;
|
||||||
state: &mut State,
|
|
||||||
builder: TextBuilder<State, Self, H>,
|
|
||||||
) -> Self::Output;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct TextOutput;
|
pub struct TextOutput;
|
||||||
impl<State: HasUi> TextBuilderOutput<State> for TextOutput {
|
impl TextBuilderOutput for TextOutput {
|
||||||
type Output = Text;
|
type Output = Text;
|
||||||
|
|
||||||
fn run<H: WidgetOption<State>>(
|
fn run<H: WidgetOption>(ui: &mut Ui, builder: TextBuilder<Self, H>) -> Self::Output {
|
||||||
state: &mut State,
|
|
||||||
builder: TextBuilder<State, Self, H>,
|
|
||||||
) -> Self::Output {
|
|
||||||
let mut buf = TextBuffer::new_empty(Metrics::new(
|
let mut buf = TextBuffer::new_empty(Metrics::new(
|
||||||
builder.attrs.font_size,
|
builder.attrs.font_size,
|
||||||
builder.attrs.line_height,
|
builder.attrs.line_height,
|
||||||
));
|
));
|
||||||
let hint = builder.hint.get(state);
|
let hint = builder.hint.get(ui);
|
||||||
let font_system = &mut state.get_mut().text.font_system;
|
let font_system = &mut ui.data().text.get_mut().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(),
|
||||||
@@ -100,25 +88,22 @@ impl<State: HasUi> TextBuilderOutput<State> for TextOutput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct TextEditOutput {
|
pub struct TextEditOutput {
|
||||||
mode: EditMode,
|
single_line: bool,
|
||||||
}
|
}
|
||||||
|
impl TextBuilderOutput for TextEditOutput {
|
||||||
impl<State: HasUi> TextBuilderOutput<State> for TextEditOutput {
|
|
||||||
type Output = TextEdit;
|
type Output = TextEdit;
|
||||||
|
|
||||||
fn run<H: WidgetOption<State>>(
|
fn run<H: WidgetOption>(ui: &mut Ui, builder: TextBuilder<Self, H>) -> Self::Output {
|
||||||
state: &mut State,
|
|
||||||
builder: TextBuilder<State, Self, H>,
|
|
||||||
) -> Self::Output {
|
|
||||||
let buf = TextBuffer::new_empty(Metrics::new(
|
let buf = TextBuffer::new_empty(Metrics::new(
|
||||||
builder.attrs.font_size,
|
builder.attrs.font_size,
|
||||||
builder.attrs.line_height,
|
builder.attrs.line_height,
|
||||||
));
|
));
|
||||||
let mut text = TextEdit::new(
|
let mut text = TextEdit::new(
|
||||||
TextView::new(buf, builder.attrs, builder.hint.get(state)),
|
TextView::new(buf, builder.attrs, builder.hint.get(ui)),
|
||||||
builder.output.mode,
|
builder.output.single_line,
|
||||||
|
ui.data().text.clone(),
|
||||||
);
|
);
|
||||||
let font_system = &mut state.get_mut().text.font_system;
|
let font_system = &mut ui.data().text.get_mut().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);
|
||||||
@@ -126,22 +111,19 @@ impl<State: HasUi> TextBuilderOutput<State> for TextEditOutput {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State, O: TextBuilderOutput<State>, H: WidgetOption<State>> FnOnce<(&mut State,)>
|
impl<O: TextBuilderOutput, H: WidgetOption> FnOnce<(&mut Ui,)> for TextBuilder<O, H> {
|
||||||
for TextBuilder<State, O, H>
|
|
||||||
{
|
|
||||||
type Output = O::Output;
|
type Output = O::Output;
|
||||||
|
|
||||||
extern "rust-call" fn call_once(self, args: (&mut State,)) -> Self::Output {
|
extern "rust-call" fn call_once(self, args: (&mut Ui,)) -> Self::Output {
|
||||||
O::run(args.0, self)
|
O::run(args.0, self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn wtext<State>(content: impl Into<String>) -> TextBuilder<State> {
|
pub fn wtext(content: impl Into<String>) -> TextBuilder {
|
||||||
TextBuilder {
|
TextBuilder {
|
||||||
content: content.into(),
|
content: content.into(),
|
||||||
attrs: TextAttrs::default(),
|
attrs: TextAttrs::default(),
|
||||||
hint: (),
|
hint: (),
|
||||||
output: TextOutput,
|
output: TextOutput,
|
||||||
state: PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::prelude::*;
|
|
||||||
use cosmic_text::{Affinity, Attrs, Cursor, FontSystem, LayoutRun, Motion};
|
|
||||||
use std::ops::{Deref, DerefMut};
|
use std::ops::{Deref, DerefMut};
|
||||||
|
|
||||||
|
use crate::prelude::*;
|
||||||
|
use cosmic_text::{Affinity, Attrs, Cursor, LayoutRun, Motion};
|
||||||
use unicode_segmentation::UnicodeSegmentation;
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
use winit::{
|
use winit::{
|
||||||
event::KeyEvent,
|
event::KeyEvent,
|
||||||
@@ -12,23 +13,19 @@ pub struct TextEdit {
|
|||||||
selection: TextSelection,
|
selection: TextSelection,
|
||||||
history: Vec<(String, TextSelection)>,
|
history: Vec<(String, TextSelection)>,
|
||||||
double_hit: Option<Cursor>,
|
double_hit: Option<Cursor>,
|
||||||
pub mode: EditMode,
|
data: TextData,
|
||||||
}
|
pub single_line: bool,
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq)]
|
|
||||||
pub enum EditMode {
|
|
||||||
SingleLine,
|
|
||||||
MultiLine,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TextEdit {
|
impl TextEdit {
|
||||||
pub fn new(view: TextView, mode: EditMode) -> Self {
|
pub fn new(view: TextView, single_line: bool, data: TextData) -> Self {
|
||||||
Self {
|
Self {
|
||||||
view,
|
view,
|
||||||
selection: Default::default(),
|
selection: Default::default(),
|
||||||
history: Default::default(),
|
history: Default::default(),
|
||||||
double_hit: None,
|
double_hit: None,
|
||||||
mode,
|
single_line,
|
||||||
|
data,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn select_content(&self, start: Cursor, end: Cursor) -> String {
|
pub fn select_content(&self, start: Cursor, end: Cursor) -> String {
|
||||||
@@ -47,6 +44,369 @@ impl TextEdit {
|
|||||||
str
|
str
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn take(&mut self) -> String {
|
||||||
|
let text = self
|
||||||
|
.buf
|
||||||
|
.lines
|
||||||
|
.drain(..)
|
||||||
|
.map(|l| l.into_text())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
self.set("");
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set(&mut self, text: &str) {
|
||||||
|
let text = self.string(text);
|
||||||
|
self.view.buf.set_text(
|
||||||
|
&mut self.data.get_mut().font_system,
|
||||||
|
&text,
|
||||||
|
&Attrs::new(),
|
||||||
|
SHAPING,
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
self.selection.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn motion(&mut self, motion: Motion, select: bool) {
|
||||||
|
if let TextSelection::Pos(cursor) = self.selection
|
||||||
|
&& let Some(new) = self.buf_motion(cursor, motion)
|
||||||
|
{
|
||||||
|
self.selection = if select {
|
||||||
|
TextSelection::Span {
|
||||||
|
start: cursor,
|
||||||
|
end: new,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
TextSelection::Pos(new)
|
||||||
|
};
|
||||||
|
} else if let TextSelection::Span { start, end } = self.selection {
|
||||||
|
if select {
|
||||||
|
if let Some(cursor) = self.buf_motion(end, motion) {
|
||||||
|
self.selection = TextSelection::Span { start, end: cursor };
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let (start, end) = sort_cursors(start, end);
|
||||||
|
match motion {
|
||||||
|
Motion::Left | Motion::LeftWord => self.selection = TextSelection::Pos(start),
|
||||||
|
Motion::Right | Motion::RightWord => self.selection = TextSelection::Pos(end),
|
||||||
|
_ => {
|
||||||
|
if let Some(cursor) = self.buf_motion(end, motion) {
|
||||||
|
self.selection = TextSelection::Pos(cursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn replace(&mut self, len: usize, text: &str) {
|
||||||
|
let text = self.string(text);
|
||||||
|
for _ in 0..len {
|
||||||
|
self.delete(false);
|
||||||
|
}
|
||||||
|
self.insert_inner(&text, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn string(&self, text: &str) -> String {
|
||||||
|
if self.single_line {
|
||||||
|
text.replace('\n', "")
|
||||||
|
} else {
|
||||||
|
text.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert(&mut self, text: &str) {
|
||||||
|
let text = self.string(text);
|
||||||
|
let mut lines = text.split('\n');
|
||||||
|
let Some(first) = lines.next() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.insert_inner(first, true);
|
||||||
|
for line in lines {
|
||||||
|
self.newline();
|
||||||
|
self.insert_inner(line, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_span(&mut self) -> bool {
|
||||||
|
if let TextSelection::Span { start, end } = self.selection {
|
||||||
|
self.delete_between(start, end);
|
||||||
|
let (start, _) = sort_cursors(start, end);
|
||||||
|
self.selection = TextSelection::Pos(start);
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_between(&mut self, start: Cursor, end: Cursor) {
|
||||||
|
let lines = &mut self.view.buf.lines;
|
||||||
|
let (start, end) = sort_cursors(start, end);
|
||||||
|
if start.line == end.line {
|
||||||
|
let line = &mut lines[start.line];
|
||||||
|
let text = line.text();
|
||||||
|
let text = text[..start.index].to_string() + &text[end.index..];
|
||||||
|
edit_line(line, text);
|
||||||
|
} else {
|
||||||
|
// start
|
||||||
|
let start_text = lines[start.line].text()[..start.index].to_string();
|
||||||
|
let end_text = &lines[end.line].text()[end.index..];
|
||||||
|
let text = start_text + end_text;
|
||||||
|
edit_line(&mut lines[start.line], text);
|
||||||
|
}
|
||||||
|
// between
|
||||||
|
let range = (start.line + 1)..=end.line;
|
||||||
|
if !range.is_empty() {
|
||||||
|
lines.splice(range, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_inner(&mut self, text: &str, mov: bool) {
|
||||||
|
self.clear_span();
|
||||||
|
if let TextSelection::Pos(cursor) = self.selection {
|
||||||
|
let line = &mut self.view.buf.lines[cursor.line];
|
||||||
|
let mut line_text = line.text().to_string();
|
||||||
|
line_text.insert_str(cursor.index, text);
|
||||||
|
edit_line(line, line_text);
|
||||||
|
if mov {
|
||||||
|
for _ in 0..text.chars().count() {
|
||||||
|
self.motion(Motion::Right, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn newline(&mut self) {
|
||||||
|
if self.single_line {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.clear_span();
|
||||||
|
if let TextSelection::Pos(cursor) = &mut self.selection {
|
||||||
|
let lines = &mut self.view.buf.lines;
|
||||||
|
let line = &mut lines[cursor.line];
|
||||||
|
let new = line.split_off(cursor.index);
|
||||||
|
cursor.line += 1;
|
||||||
|
lines.insert(cursor.line, new);
|
||||||
|
cursor.index = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn backspace(&mut self, word: bool) {
|
||||||
|
if !self.clear_span()
|
||||||
|
&& let TextSelection::Pos(cursor) = &mut self.selection
|
||||||
|
&& (cursor.index != 0 || cursor.line != 0)
|
||||||
|
{
|
||||||
|
self.motion(if word { Motion::LeftWord } else { Motion::Left }, false);
|
||||||
|
self.delete(word);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete(&mut self, word: bool) {
|
||||||
|
if self.clear_span() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let TextSelection::Pos(cursor) = &mut self.selection {
|
||||||
|
if word {
|
||||||
|
let start = *cursor;
|
||||||
|
if let Some(end) = self.buf_motion(start, Motion::RightWord) {
|
||||||
|
self.delete_between(start, end);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let lines = &mut self.view.buf.lines;
|
||||||
|
let line = &mut lines[cursor.line];
|
||||||
|
if cursor.index == line.text().len() {
|
||||||
|
if cursor.line == lines.len() - 1 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let add = lines.remove(cursor.line + 1).into_text();
|
||||||
|
let line = &mut lines[cursor.line];
|
||||||
|
let mut cur = line.text().to_string();
|
||||||
|
cur.push_str(&add);
|
||||||
|
edit_line(line, cur);
|
||||||
|
} else {
|
||||||
|
let mut text = line.text().to_string();
|
||||||
|
text.remove(cursor.index);
|
||||||
|
edit_line(line, text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn buf_motion(&mut self, cursor: Cursor, motion: Motion) -> Option<Cursor> {
|
||||||
|
self.view
|
||||||
|
.buf
|
||||||
|
.cursor_motion(
|
||||||
|
&mut self.data.get_mut().font_system,
|
||||||
|
cursor,
|
||||||
|
None,
|
||||||
|
motion,
|
||||||
|
)
|
||||||
|
.map(|r| r.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn select_word_at(&mut self, cursor: Cursor) {
|
||||||
|
if let (Some(start), Some(end)) = (
|
||||||
|
self.buf_motion(cursor, Motion::LeftWord),
|
||||||
|
self.buf_motion(cursor, Motion::RightWord),
|
||||||
|
) {
|
||||||
|
self.selection = TextSelection::Span { start, end };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn select_line_at(&mut self, cursor: Cursor) {
|
||||||
|
let end = self.buf.lines[cursor.line].text().len();
|
||||||
|
self.selection = TextSelection::Span {
|
||||||
|
start: Cursor::new(cursor.line, 0),
|
||||||
|
end: Cursor::new(cursor.line, end),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn select(&mut self, pos: Vec2, size: Vec2, drag: bool, recent: bool) {
|
||||||
|
let pos = pos - self.region().top_left().to_abs(size);
|
||||||
|
let hit = self.buf.hit(pos.x, pos.y);
|
||||||
|
let sel = &mut self.selection;
|
||||||
|
match sel {
|
||||||
|
TextSelection::None => {
|
||||||
|
if !drag && let Some(hit) = hit {
|
||||||
|
*sel = TextSelection::Pos(hit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextSelection::Pos(pos) => match (hit, drag) {
|
||||||
|
(None, false) => *sel = TextSelection::None,
|
||||||
|
(None, true) => (),
|
||||||
|
(Some(hit), false) => {
|
||||||
|
if recent && hit == *pos {
|
||||||
|
self.double_hit = Some(hit);
|
||||||
|
return self.select_word_at(hit);
|
||||||
|
} else {
|
||||||
|
*pos = hit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Some(end), true) => *sel = TextSelection::Span { start: *pos, end },
|
||||||
|
},
|
||||||
|
TextSelection::Span { start, end } => match (hit, drag) {
|
||||||
|
(None, false) => *sel = TextSelection::None,
|
||||||
|
(None, true) => *sel = TextSelection::Pos(*start),
|
||||||
|
(Some(hit), false) => {
|
||||||
|
if recent
|
||||||
|
&& let Some(double) = self.double_hit
|
||||||
|
&& double == hit
|
||||||
|
{
|
||||||
|
return self.select_line_at(hit);
|
||||||
|
} else {
|
||||||
|
*sel = TextSelection::Pos(hit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Some(hit), true) => *end = hit,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if let TextSelection::Span { start, end } = sel
|
||||||
|
&& start == end
|
||||||
|
{
|
||||||
|
*sel = TextSelection::Pos(*start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deselect(&mut self) {
|
||||||
|
self.selection = TextSelection::None;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_event(&mut self, event: &KeyEvent, modifiers: &Modifiers) -> TextInputResult {
|
||||||
|
let old = (self.content(), self.selection);
|
||||||
|
let mut undo = false;
|
||||||
|
let res = self.apply_event_inner(event, modifiers, &mut undo);
|
||||||
|
if undo && let Some((old, selection)) = self.history.pop() {
|
||||||
|
self.set(&old);
|
||||||
|
self.selection = selection;
|
||||||
|
} else if self.content() != old.0 {
|
||||||
|
self.history.push(old);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_event_inner(
|
||||||
|
&mut self,
|
||||||
|
event: &KeyEvent,
|
||||||
|
modifiers: &Modifiers,
|
||||||
|
undo: &mut bool,
|
||||||
|
) -> TextInputResult {
|
||||||
|
match &event.logical_key {
|
||||||
|
Key::Named(named) => match named {
|
||||||
|
NamedKey::Backspace => self.backspace(modifiers.control),
|
||||||
|
NamedKey::Delete => self.delete(modifiers.control),
|
||||||
|
NamedKey::Space => self.insert(" "),
|
||||||
|
NamedKey::Enter => {
|
||||||
|
if modifiers.shift {
|
||||||
|
self.newline();
|
||||||
|
} else {
|
||||||
|
return TextInputResult::Submit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NamedKey::ArrowRight => {
|
||||||
|
if modifiers.control {
|
||||||
|
self.motion(Motion::RightWord, modifiers.shift)
|
||||||
|
} else {
|
||||||
|
self.motion(Motion::Right, modifiers.shift)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NamedKey::ArrowLeft => {
|
||||||
|
if modifiers.control {
|
||||||
|
self.motion(Motion::LeftWord, modifiers.shift)
|
||||||
|
} else {
|
||||||
|
self.motion(Motion::Left, modifiers.shift)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NamedKey::ArrowUp => self.motion(Motion::Up, modifiers.shift),
|
||||||
|
NamedKey::ArrowDown => self.motion(Motion::Down, modifiers.shift),
|
||||||
|
NamedKey::Escape => {
|
||||||
|
self.deselect();
|
||||||
|
return TextInputResult::Unfocus;
|
||||||
|
}
|
||||||
|
_ => return TextInputResult::Unused,
|
||||||
|
},
|
||||||
|
Key::Character(text) => {
|
||||||
|
if modifiers.control {
|
||||||
|
match text.as_str() {
|
||||||
|
"v" => return TextInputResult::Paste,
|
||||||
|
"c" => {
|
||||||
|
if let TextSelection::Span { start, end } = self.selection {
|
||||||
|
let content = self.select_content(start, end);
|
||||||
|
return TextInputResult::Copy(content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"x" => {
|
||||||
|
if let TextSelection::Span { start, end } = self.selection {
|
||||||
|
let content = self.select_content(start, end);
|
||||||
|
self.clear_span();
|
||||||
|
return TextInputResult::Copy(content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"a" => {
|
||||||
|
if !self.buf.lines[0].text().is_empty() || self.buf.lines.len() > 1 {
|
||||||
|
let lines = &self.buf.lines;
|
||||||
|
let last_line = lines.len() - 1;
|
||||||
|
let last_idx = lines[last_line].text().len();
|
||||||
|
self.selection = TextSelection::Span {
|
||||||
|
start: Cursor::new(0, 0),
|
||||||
|
end: Cursor::new(last_line, last_idx),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"z" => {
|
||||||
|
*undo = true;
|
||||||
|
}
|
||||||
|
_ => self.insert(text),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.insert(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return TextInputResult::Unused,
|
||||||
|
}
|
||||||
|
TextInputResult::Used
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Widget for TextEdit {
|
impl Widget for TextEdit {
|
||||||
@@ -180,373 +540,6 @@ fn cursor_pos(cursor: Cursor, buf: &TextBuffer) -> Option<Vec2> {
|
|||||||
prev
|
prev
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct TextEditCtx<'a> {
|
|
||||||
pub text: &'a mut TextEdit,
|
|
||||||
pub font_system: &'a mut FontSystem,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TextEditCtx<'a> {
|
|
||||||
pub fn take(&mut self) -> String {
|
|
||||||
let text = self
|
|
||||||
.text
|
|
||||||
.buf
|
|
||||||
.lines
|
|
||||||
.drain(..)
|
|
||||||
.map(|l| l.into_text())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
self.text
|
|
||||||
.buf
|
|
||||||
.set_text(self.font_system, "", &Attrs::new(), SHAPING, None);
|
|
||||||
self.text.selection.clear();
|
|
||||||
text
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set(&mut self, text: &str) {
|
|
||||||
let text = self.string(text);
|
|
||||||
self.text
|
|
||||||
.buf
|
|
||||||
.set_text(self.font_system, &text, &Attrs::new(), SHAPING, None);
|
|
||||||
self.text.selection.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn motion(&mut self, motion: Motion, select: bool) {
|
|
||||||
if let TextSelection::Pos(cursor) = self.text.selection
|
|
||||||
&& let Some(new) = self.buf_motion(cursor, motion)
|
|
||||||
{
|
|
||||||
if select {
|
|
||||||
self.text.selection = TextSelection::Span {
|
|
||||||
start: cursor,
|
|
||||||
end: new,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
self.text.selection = TextSelection::Pos(new);
|
|
||||||
}
|
|
||||||
} else if let TextSelection::Span { start, end } = self.text.selection {
|
|
||||||
if select {
|
|
||||||
if let Some(cursor) = self.buf_motion(end, motion) {
|
|
||||||
self.text.selection = TextSelection::Span { start, end: cursor };
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let (start, end) = sort_cursors(start, end);
|
|
||||||
let sel = &mut self.text.selection;
|
|
||||||
match motion {
|
|
||||||
Motion::Left | Motion::LeftWord => *sel = TextSelection::Pos(start),
|
|
||||||
Motion::Right | Motion::RightWord => *sel = TextSelection::Pos(end),
|
|
||||||
_ => {
|
|
||||||
if let Some(cursor) = self.buf_motion(end, motion) {
|
|
||||||
self.text.selection = TextSelection::Pos(cursor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn replace(&mut self, len: usize, text: &str) {
|
|
||||||
let text = self.string(text);
|
|
||||||
for _ in 0..len {
|
|
||||||
self.delete(false);
|
|
||||||
}
|
|
||||||
self.insert_inner(&text, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn string(&self, text: &str) -> String {
|
|
||||||
if self.text.mode == EditMode::SingleLine {
|
|
||||||
text.replace('\n', "")
|
|
||||||
} else {
|
|
||||||
text.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn insert(&mut self, text: &str) {
|
|
||||||
let text = self.string(text);
|
|
||||||
let mut lines = text.split('\n');
|
|
||||||
let Some(first) = lines.next() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
self.insert_inner(first, true);
|
|
||||||
for line in lines {
|
|
||||||
self.newline();
|
|
||||||
self.insert_inner(line, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear_span(&mut self) -> bool {
|
|
||||||
if let TextSelection::Span { start, end } = self.text.selection {
|
|
||||||
self.delete_between(start, end);
|
|
||||||
let (start, _) = sort_cursors(start, end);
|
|
||||||
self.text.selection = TextSelection::Pos(start);
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete_between(&mut self, start: Cursor, end: Cursor) {
|
|
||||||
let lines = &mut self.text.view.buf.lines;
|
|
||||||
let (start, end) = sort_cursors(start, end);
|
|
||||||
if start.line == end.line {
|
|
||||||
let line = &mut lines[start.line];
|
|
||||||
let text = line.text();
|
|
||||||
let text = text[..start.index].to_string() + &text[end.index..];
|
|
||||||
edit_line(line, text);
|
|
||||||
} else {
|
|
||||||
// start
|
|
||||||
let start_text = lines[start.line].text()[..start.index].to_string();
|
|
||||||
let end_text = &lines[end.line].text()[end.index..];
|
|
||||||
let text = start_text + end_text;
|
|
||||||
edit_line(&mut lines[start.line], text);
|
|
||||||
}
|
|
||||||
// between
|
|
||||||
let range = (start.line + 1)..=end.line;
|
|
||||||
if !range.is_empty() {
|
|
||||||
lines.splice(range, None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert_inner(&mut self, text: &str, mov: bool) {
|
|
||||||
self.clear_span();
|
|
||||||
if let TextSelection::Pos(cursor) = &mut self.text.selection {
|
|
||||||
let line = &mut self.text.view.buf.lines[cursor.line];
|
|
||||||
let mut line_text = line.text().to_string();
|
|
||||||
line_text.insert_str(cursor.index, text);
|
|
||||||
edit_line(line, line_text);
|
|
||||||
if mov {
|
|
||||||
for _ in 0..text.chars().count() {
|
|
||||||
self.motion(Motion::Right, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn newline(&mut self) {
|
|
||||||
if self.text.mode == EditMode::SingleLine {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.clear_span();
|
|
||||||
if let TextSelection::Pos(cursor) = &mut self.text.selection {
|
|
||||||
let lines = &mut self.text.view.buf.lines;
|
|
||||||
let line = &mut lines[cursor.line];
|
|
||||||
let new = line.split_off(cursor.index);
|
|
||||||
cursor.line += 1;
|
|
||||||
lines.insert(cursor.line, new);
|
|
||||||
cursor.index = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn backspace(&mut self, word: bool) {
|
|
||||||
if !self.clear_span()
|
|
||||||
&& let TextSelection::Pos(cursor) = &mut self.text.selection
|
|
||||||
&& (cursor.index != 0 || cursor.line != 0)
|
|
||||||
{
|
|
||||||
self.motion(if word { Motion::LeftWord } else { Motion::Left }, false);
|
|
||||||
self.delete(word);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn delete(&mut self, word: bool) {
|
|
||||||
if !self.clear_span()
|
|
||||||
&& let TextSelection::Pos(cursor) = &mut self.text.selection
|
|
||||||
{
|
|
||||||
if word {
|
|
||||||
let start = *cursor;
|
|
||||||
if let Some(end) = self.buf_motion(start, Motion::RightWord) {
|
|
||||||
self.delete_between(start, end);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let lines = &mut self.text.view.buf.lines;
|
|
||||||
let line = &mut lines[cursor.line];
|
|
||||||
if cursor.index == line.text().len() {
|
|
||||||
if cursor.line == lines.len() - 1 {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let add = lines.remove(cursor.line + 1).into_text();
|
|
||||||
let line = &mut lines[cursor.line];
|
|
||||||
let mut cur = line.text().to_string();
|
|
||||||
cur.push_str(&add);
|
|
||||||
edit_line(line, cur);
|
|
||||||
} else {
|
|
||||||
let mut text = line.text().to_string();
|
|
||||||
text.remove(cursor.index);
|
|
||||||
edit_line(line, text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn buf_motion(&mut self, cursor: Cursor, motion: Motion) -> Option<Cursor> {
|
|
||||||
self.text
|
|
||||||
.buf
|
|
||||||
.cursor_motion(self.font_system, cursor, None, motion)
|
|
||||||
.map(|r| r.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn select_word_at(&mut self, cursor: Cursor) {
|
|
||||||
if let (Some(start), Some(end)) = (
|
|
||||||
self.buf_motion(cursor, Motion::LeftWord),
|
|
||||||
self.buf_motion(cursor, Motion::RightWord),
|
|
||||||
) {
|
|
||||||
self.text.selection = TextSelection::Span { start, end };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn select_line_at(&mut self, cursor: Cursor) {
|
|
||||||
let end = self.text.buf.lines[cursor.line].text().len();
|
|
||||||
self.text.selection = TextSelection::Span {
|
|
||||||
start: Cursor::new(cursor.line, 0),
|
|
||||||
end: Cursor::new(cursor.line, end),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn select(&mut self, pos: Vec2, size: Vec2, drag: bool, recent: bool) {
|
|
||||||
let pos = pos - self.text.region().top_left().to_abs(size);
|
|
||||||
let hit = self.text.buf.hit(pos.x, pos.y);
|
|
||||||
let sel = &mut self.text.selection;
|
|
||||||
match sel {
|
|
||||||
TextSelection::None => {
|
|
||||||
if !drag && let Some(hit) = hit {
|
|
||||||
*sel = TextSelection::Pos(hit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TextSelection::Pos(pos) => match (hit, drag) {
|
|
||||||
(None, false) => *sel = TextSelection::None,
|
|
||||||
(None, true) => (),
|
|
||||||
(Some(hit), false) => {
|
|
||||||
if recent && hit == *pos {
|
|
||||||
self.text.double_hit = Some(hit);
|
|
||||||
return self.select_word_at(hit);
|
|
||||||
} else {
|
|
||||||
*pos = hit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(Some(end), true) => *sel = TextSelection::Span { start: *pos, end },
|
|
||||||
},
|
|
||||||
TextSelection::Span { start, end } => match (hit, drag) {
|
|
||||||
(None, false) => *sel = TextSelection::None,
|
|
||||||
(None, true) => *sel = TextSelection::Pos(*start),
|
|
||||||
(Some(hit), false) => {
|
|
||||||
if recent
|
|
||||||
&& let Some(double) = self.text.double_hit
|
|
||||||
&& double == hit
|
|
||||||
{
|
|
||||||
return self.select_line_at(hit);
|
|
||||||
} else {
|
|
||||||
*sel = TextSelection::Pos(hit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(Some(hit), true) => *end = hit,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
if let TextSelection::Span { start, end } = sel
|
|
||||||
&& start == end
|
|
||||||
{
|
|
||||||
*sel = TextSelection::Pos(*start);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn deselect(&mut self) {
|
|
||||||
self.text.selection = TextSelection::None;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn apply_event(&mut self, event: &KeyEvent, modifiers: &Modifiers) -> TextInputResult {
|
|
||||||
let old = (self.text.content(), self.text.selection);
|
|
||||||
let mut undo = false;
|
|
||||||
let res = self.apply_event_inner(event, modifiers, &mut undo);
|
|
||||||
if undo && let Some((old, selection)) = self.text.history.pop() {
|
|
||||||
self.set(&old);
|
|
||||||
self.text.selection = selection;
|
|
||||||
} else if self.text.content() != old.0 {
|
|
||||||
self.text.history.push(old);
|
|
||||||
}
|
|
||||||
res
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_event_inner(
|
|
||||||
&mut self,
|
|
||||||
event: &KeyEvent,
|
|
||||||
modifiers: &Modifiers,
|
|
||||||
undo: &mut bool,
|
|
||||||
) -> TextInputResult {
|
|
||||||
match &event.logical_key {
|
|
||||||
Key::Named(named) => match named {
|
|
||||||
NamedKey::Backspace => self.backspace(modifiers.control),
|
|
||||||
NamedKey::Delete => self.delete(modifiers.control),
|
|
||||||
NamedKey::Space => self.insert(" "),
|
|
||||||
NamedKey::Enter => {
|
|
||||||
if modifiers.shift {
|
|
||||||
self.newline();
|
|
||||||
} else {
|
|
||||||
return TextInputResult::Submit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
NamedKey::ArrowRight => {
|
|
||||||
if modifiers.control {
|
|
||||||
self.motion(Motion::RightWord, modifiers.shift)
|
|
||||||
} else {
|
|
||||||
self.motion(Motion::Right, modifiers.shift)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
NamedKey::ArrowLeft => {
|
|
||||||
if modifiers.control {
|
|
||||||
self.motion(Motion::LeftWord, modifiers.shift)
|
|
||||||
} else {
|
|
||||||
self.motion(Motion::Left, modifiers.shift)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
NamedKey::ArrowUp => self.motion(Motion::Up, modifiers.shift),
|
|
||||||
NamedKey::ArrowDown => self.motion(Motion::Down, modifiers.shift),
|
|
||||||
NamedKey::Escape => {
|
|
||||||
self.deselect();
|
|
||||||
return TextInputResult::Unfocus;
|
|
||||||
}
|
|
||||||
_ => return TextInputResult::Unused,
|
|
||||||
},
|
|
||||||
Key::Character(text) => {
|
|
||||||
if modifiers.control {
|
|
||||||
match text.as_str() {
|
|
||||||
"v" => return TextInputResult::Paste,
|
|
||||||
"c" => {
|
|
||||||
if let TextSelection::Span { start, end } = self.text.selection {
|
|
||||||
let content = self.text.select_content(start, end);
|
|
||||||
return TextInputResult::Copy(content);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"x" => {
|
|
||||||
if let TextSelection::Span { start, end } = self.text.selection {
|
|
||||||
let content = self.text.select_content(start, end);
|
|
||||||
self.clear_span();
|
|
||||||
return TextInputResult::Copy(content);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"a" => {
|
|
||||||
if !self.text.buf.lines[0].text().is_empty()
|
|
||||||
|| self.text.buf.lines.len() > 1
|
|
||||||
{
|
|
||||||
let lines = &self.text.buf.lines;
|
|
||||||
let last_line = lines.len() - 1;
|
|
||||||
let last_idx = lines[last_line].text().len();
|
|
||||||
self.text.selection = TextSelection::Span {
|
|
||||||
start: Cursor::new(0, 0),
|
|
||||||
end: Cursor::new(last_line, last_idx),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"z" => {
|
|
||||||
*undo = true;
|
|
||||||
}
|
|
||||||
_ => self.insert(text),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.insert(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => return TextInputResult::Unused,
|
|
||||||
}
|
|
||||||
TextInputResult::Used
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct Modifiers {
|
pub struct Modifiers {
|
||||||
pub shift: bool,
|
pub shift: bool,
|
||||||
@@ -615,17 +608,3 @@ impl DerefMut for TextEdit {
|
|||||||
&mut self.view
|
&mut self.view
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait TextEditable {
|
|
||||||
fn edit<'a>(&self, ui: &'a mut impl HasUi) -> TextEditCtx<'a>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<I: IdLike<Widget = TextEdit>> TextEditable for I {
|
|
||||||
fn edit<'a>(&self, ui: &'a mut impl HasUi) -> TextEditCtx<'a> {
|
|
||||||
let ui = ui.ui_mut();
|
|
||||||
TextEditCtx {
|
|
||||||
text: ui.widgets.get_mut(self).unwrap(),
|
|
||||||
font_system: &mut ui.text.font_system,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,9 +3,8 @@ mod edit;
|
|||||||
|
|
||||||
pub use build::*;
|
pub use build::*;
|
||||||
pub use edit::*;
|
pub use edit::*;
|
||||||
use iris_core::util::MutDetect;
|
|
||||||
|
|
||||||
use crate::prelude::*;
|
use crate::{prelude::*, util::MutDetect};
|
||||||
use cosmic_text::{Attrs, BufferLine, Cursor, Metrics, Shaping};
|
use cosmic_text::{Attrs, BufferLine, Cursor, Metrics, Shaping};
|
||||||
use std::ops::{Deref, DerefMut};
|
use std::ops::{Deref, DerefMut};
|
||||||
|
|
||||||
@@ -68,9 +67,12 @@ impl TextView {
|
|||||||
return tex.clone();
|
return tex.clone();
|
||||||
}
|
}
|
||||||
self.width = width;
|
self.width = width;
|
||||||
let font_system = &mut ctx.text.font_system;
|
let mut text_data = ctx.text.get_mut();
|
||||||
self.attrs.apply(font_system, &mut self.buf, width);
|
self.attrs
|
||||||
self.buf.shape_until_scroll(font_system, false);
|
.apply(&mut text_data.font_system, &mut self.buf, width);
|
||||||
|
self.buf
|
||||||
|
.shape_until_scroll(&mut text_data.font_system, false);
|
||||||
|
drop(text_data);
|
||||||
let tex = ctx.draw_text(&mut self.buf, &self.attrs);
|
let tex = ctx.draw_text(&mut self.buf, &self.attrs);
|
||||||
self.tex = Some(tex.clone());
|
self.tex = Some(tex.clone());
|
||||||
self.attrs.changed = false;
|
self.attrs.changed = false;
|
||||||
@@ -137,7 +139,7 @@ impl Text {
|
|||||||
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(
|
||||||
&mut ctx.text.font_system,
|
&mut ctx.text.get_mut().font_system,
|
||||||
&self.content,
|
&self.content,
|
||||||
&Attrs::new().family(self.view.attrs.family),
|
&Attrs::new().family(self.view.attrs.family),
|
||||||
SHAPING,
|
SHAPING,
|
||||||
|
|||||||
@@ -1,149 +1,147 @@
|
|||||||
use super::*;
|
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
|
use iris_macro::widget_trait;
|
||||||
|
|
||||||
// these methods should "not require any context" (require unit) because they're in core
|
// these methods should "not require any context" (require unit) because they're in core
|
||||||
|
event_ctx!(());
|
||||||
|
|
||||||
widget_trait! {
|
widget_trait! {
|
||||||
pub trait CoreWidget<State: HasUi + StateLike<State> + 'static>;
|
pub trait CoreWidget;
|
||||||
|
|
||||||
fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<State, Pad> {
|
fn pad(self, padding: impl Into<Padding>) -> impl WidgetFn<Pad> {
|
||||||
|state| Pad {
|
|ui| Pad {
|
||||||
padding: padding.into(),
|
padding: padding.into(),
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn align(self, align: impl Into<Align>) -> impl WidgetFn<State, Aligned> {
|
fn align(self, align: impl Into<Align>) -> impl WidgetFn<Aligned> {
|
||||||
move |state| Aligned {
|
move |ui| Aligned {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
align: align.into(),
|
align: align.into(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn center(self) -> impl WidgetFn<State, Aligned> {
|
fn center(self) -> impl WidgetFn<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<WL::Widget> {
|
||||||
|state| {
|
|ui| {
|
||||||
let id = self.add(state);
|
let id = self.add(ui);
|
||||||
state.get_mut().set_label(id, label.into());
|
id.set_label(label);
|
||||||
id
|
id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sized(self, size: impl Into<Size>) -> impl WidgetFn<State, Sized> {
|
fn sized(self, size: impl Into<Size>) -> impl WidgetFn<Sized> {
|
||||||
let size = size.into();
|
let size = size.into();
|
||||||
move |state| Sized {
|
move |ui| Sized {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
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> {
|
fn max_width(self, len: impl Into<Len>) -> impl WidgetFn<MaxSize> {
|
||||||
let len = len.into();
|
let len = len.into();
|
||||||
move |state| MaxSize {
|
move |ui| MaxSize {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
x: Some(len),
|
x: Some(len),
|
||||||
y: None,
|
y: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn max_height(self, len: impl Into<Len>) -> impl WidgetFn<State, MaxSize> {
|
fn max_height(self, len: impl Into<Len>) -> impl WidgetFn<MaxSize> {
|
||||||
let len = len.into();
|
let len = len.into();
|
||||||
move |state| MaxSize {
|
move |ui| MaxSize {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
x: None,
|
x: None,
|
||||||
y: Some(len),
|
y: Some(len),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn width(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized> {
|
fn width(self, len: impl Into<Len>) -> impl WidgetFn<Sized> {
|
||||||
let len = len.into();
|
let len = len.into();
|
||||||
move |state| Sized {
|
move |ui| Sized {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
x: Some(len),
|
x: Some(len),
|
||||||
y: None,
|
y: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn height(self, len: impl Into<Len>) -> impl WidgetFn<State, Sized> {
|
fn height(self, len: impl Into<Len>) -> impl WidgetFn<Sized> {
|
||||||
let len = len.into();
|
let len = len.into();
|
||||||
move |state| Sized {
|
move |ui| Sized {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
x: None,
|
x: None,
|
||||||
y: Some(len),
|
y: Some(len),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn offset(self, amt: impl Into<UiVec2>) -> impl WidgetFn<State, Offset> {
|
fn offset(self, amt: impl Into<UiVec2>) -> impl WidgetFn<Offset> {
|
||||||
move |state| Offset {
|
move |ui| Offset {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
amt: amt.into(),
|
amt: amt.into(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scrollable(self) -> impl WidgetIdFn<State, Scroll> where State: HasEvents {
|
fn scroll(self) -> impl WidgetIdFn<Scroll> {
|
||||||
use eventable::*;
|
move |ui| {
|
||||||
move |state| {
|
Scroll::new(self.add(ui), Axis::Y)
|
||||||
Scroll::new(self.add_strong(state), Axis::Y)
|
.on(CursorSense::Scroll, |ctx| {
|
||||||
.on(CursorSense::Scroll, |ctx: &mut EventIdCtx<'_, State::State, CursorData<'_>, Scroll>| {
|
let s = &mut *ctx.widget.get_mut();
|
||||||
let delta = ctx.data.scroll_delta.y * 50.0;
|
s.scroll(ctx.data.scroll_delta.y * 50.0);
|
||||||
ctx.widget().scroll(delta);
|
|
||||||
})
|
})
|
||||||
.add(state)
|
.add(ui)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn masked(self) -> impl WidgetFn<State, Masked> {
|
fn masked(self) -> impl WidgetFn<Masked> {
|
||||||
move |state| Masked {
|
move |ui| Masked {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn background<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack> {
|
fn background<T,>(self, w: impl WidgetLike<T>) -> impl WidgetFn<Stack> {
|
||||||
move |state| Stack {
|
move |ui| Stack {
|
||||||
children: vec![w.add_strong(state), self.add_strong(state)],
|
children: vec![w.add(ui), self.add(ui)],
|
||||||
size: StackSize::Child(1),
|
size: StackSize::Child(1),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn foreground<T>(self, w: impl WidgetLike<State, T>) -> impl WidgetFn<State, Stack> {
|
fn foreground<T,>(self, w: impl WidgetLike<T>) -> impl WidgetFn<Stack> {
|
||||||
move |state| Stack {
|
move |ui| Stack {
|
||||||
children: vec![self.add_strong(state), w.add_strong(state)],
|
children: vec![self.add(ui), w.add(ui)],
|
||||||
size: StackSize::Child(0),
|
size: StackSize::Child(0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn layer_offset(self, offset: usize) -> impl WidgetFn<State, LayerOffset> {
|
fn layer_offset(self, offset: usize) -> impl WidgetFn<LayerOffset> {
|
||||||
move |state| LayerOffset {
|
move |ui| LayerOffset {
|
||||||
inner: self.add_strong(state),
|
inner: self.add(ui),
|
||||||
offset,
|
offset,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn to_any(self) -> impl WidgetIdFn<State> {
|
fn to_any(self) -> impl WidgetRet {
|
||||||
|state| self.add(state)
|
|ui| self.add(ui)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_ptr(self, ptr: WidgetRef<WidgetPtr>, state: &mut State) {
|
fn set_ptr(self, ptr: &WidgetHandle<WidgetPtr>, ui: &mut Ui) {
|
||||||
let id = self.add_strong(state);
|
ptr.get_mut().inner = Some(self.add(ui));
|
||||||
state.get_mut()[ptr].inner = Some(id);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait CoreWidgetArr<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag> {
|
pub trait CoreWidgetArr<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> {
|
||||||
fn span(self, dir: Dir) -> SpanBuilder<State, LEN, Wa, Tag>;
|
fn span(self, dir: Dir) -> SpanBuilder<LEN, Wa, Tag>;
|
||||||
fn stack(self) -> StackBuilder<State, LEN, Wa, Tag>;
|
fn stack(self) -> StackBuilder<LEN, Wa, Tag>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<State, const LEN: usize, Wa: WidgetArrLike<State, LEN, Tag>, Tag>
|
impl<const LEN: usize, Wa: WidgetArrLike<LEN, Tag>, Tag> CoreWidgetArr<LEN, Wa, Tag> for Wa {
|
||||||
CoreWidgetArr<State, LEN, Wa, Tag> for Wa
|
fn span(self, dir: Dir) -> SpanBuilder<LEN, Wa, Tag> {
|
||||||
{
|
|
||||||
fn span(self, dir: Dir) -> SpanBuilder<State, LEN, Wa, Tag> {
|
|
||||||
SpanBuilder::new(self, dir)
|
SpanBuilder::new(self, dir)
|
||||||
}
|
}
|
||||||
fn stack(self) -> StackBuilder<State, LEN, Wa, Tag> {
|
fn stack(self) -> StackBuilder<LEN, Wa, Tag> {
|
||||||
StackBuilder::new(self)
|
StackBuilder::new(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user