RE ADD CONTEXT

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

View File

@@ -3,213 +3,227 @@ use std::{cell::RefCell, rc::Rc};
use cosmic_text::Family;
use iris::prelude::*;
use len_fns::*;
use winit::event::WindowEvent;
use winit::{event::WindowEvent, event_loop::ActiveEventLoop, window::WindowAttributes};
fn main() {
DefaultApp::<Client>::run();
App::<Client>::run();
}
#[derive(HasUi, HasUiState)]
pub struct Client {
info: WidgetRef<Text>,
ui: Ui<Self>,
ui_state: UiState<Self>,
info: WidgetRef<Self, Text<Self>>,
}
event_ctx!(Client);
impl DefaultAppState for Client {
fn new(ui: &mut Ui, _state: &UiState, _proxy: Proxy<Self::Event>) -> Self {
let rrect = rect(Color::WHITE).radius(20);
let pad_test = (
rrect.color(Color::BLUE),
(
rrect
.color(Color::RED)
.sized((100, 100))
.center()
.width(rest(2)),
fn new(event_loop: &ActiveEventLoop, _proxy: Proxy<Self::Event>) -> Self {
let mut ui = Ui::new();
let window = event_loop
.create_window(WindowAttributes::default())
.unwrap();
let info;
{
let ui = &mut ui;
let rrect = rect(Color::WHITE).radius(20);
let pad_test = (
rrect.color(Color::BLUE),
(
rrect.color(Color::ORANGE),
rrect.color(Color::LIME).pad(10.0),
rrect
.color(Color::RED)
.sized((100, 100))
.center()
.width(rest(2)),
(
rrect.color(Color::ORANGE),
rrect.color(Color::LIME).pad(10.0),
)
.span(Dir::RIGHT)
.width(rest(2)),
rrect.color(Color::YELLOW),
)
.span(Dir::RIGHT)
.width(rest(2)),
rrect.color(Color::YELLOW),
.pad(10)
.width(rest(3)),
)
.span(Dir::RIGHT)
.pad(10)
.width(rest(3)),
)
.span(Dir::RIGHT)
.handles(ui);
.handles(ui);
let span_test = (
rrect.color(Color::GREEN).width(100),
rrect.color(Color::ORANGE),
rrect.color(Color::CYAN),
rrect.color(Color::BLUE).width(rel(0.5)),
rrect.color(Color::MAGENTA).width(100),
rrect.color(Color::RED).width(100),
)
.span(Dir::LEFT)
.add(ui);
let span_add = Span::empty(Dir::RIGHT).handles(ui);
let add_button = rect(Color::LIME)
.radius(30)
.on(CursorSense::click(), move |mut ctx| {
let child = ctx
.ui
.add(image(include_bytes!("assets/sungals.png")).center());
ctx[span_add.r].children.push(child);
})
.sized((150, 150))
.align(Align::BOT_RIGHT);
let del_button = rect(Color::RED)
.radius(30)
.on(CursorSense::click(), move |mut ctx| {
ctx[span_add.r].children.pop();
})
.sized((150, 150))
.align(Align::BOT_LEFT);
let span_add_test = (span_add.h, add_button, del_button).stack().add(ui);
let btext = |content| wtext(content).size(30);
let text_test = (
btext("this is a").align(Align::LEFT),
btext("teeeeeeeest").align(Align::RIGHT),
btext("okkk\nokkkkkk!").align(Align::LEFT),
btext("hmm"),
btext("a"),
(
btext("'").family(Family::Monospace).align(Align::TOP),
btext("'").family(Family::Monospace),
btext(":gamer mode").family(Family::Monospace),
rect(Color::CYAN).sized((10, 10)).center(),
rect(Color::RED).sized((100, 100)).center(),
rect(Color::PURPLE).sized((50, 50)).align(Align::TOP),
let span_test = (
rrect.color(Color::GREEN).width(100),
rrect.color(Color::ORANGE),
rrect.color(Color::CYAN),
rrect.color(Color::BLUE).width(rel(0.5)),
rrect.color(Color::MAGENTA).width(100),
rrect.color(Color::RED).width(100),
)
.span(Dir::RIGHT)
.center(),
wtext("pretty cool right?").size(50),
)
.span(Dir::DOWN)
.add(ui);
.span(Dir::LEFT)
.add(ui);
let texts = Span::empty(Dir::DOWN).gap(10).handles(ui);
let msg_area = texts.h.scroll().masked().background(rect(Color::SKY));
let add_text = wtext("add")
.editable(false)
.text_align(Align::LEFT)
.size(30)
.attr::<Selectable>(())
.on(Submit, move |ctx| {
let content = ctx.widget.edit(ctx.ui).take();
let text = wtext(content)
.editable(false)
.size(30)
.text_align(Align::LEFT)
.wrap(true)
.attr::<Selectable>(());
let msg_box = text.background(rect(Color::WHITE.darker(0.5))).add(ctx.ui);
ctx.ui[texts.r].children.push(msg_box);
})
.handles(ui);
let text_edit_scroll = (
msg_area.height(rest(1)),
(
Rect::new(Color::WHITE.darker(0.9)),
(
add_text.h.width(rest(1)),
Rect::new(Color::GREEN)
.on(CursorSense::click(), move |ctx| {
ctx.ui
.run_event::<Submit, _>(ctx.state, add_text.r, &mut ());
})
.sized((40, 40)),
)
.span(Dir::RIGHT)
.pad(10),
)
.stack()
.size(StackSize::Child(1))
.layer_offset(1)
.align(Align::BOT),
)
.span(Dir::DOWN)
.add(ui);
let span_add = Span::empty(Dir::RIGHT).handles(ui);
let main = WidgetPtr::new().handles(ui);
let vals = Rc::new(RefCell::new((0, Vec::new())));
let mut switch_button = |color, to: WidgetHandle, label| {
let vec = &mut vals.borrow_mut().1;
let i = vec.len();
if vec.is_empty() {
vec.push(None);
ui[main.r].set(to);
} else {
vec.push(Some(to));
}
let vals = vals.clone();
let rect = rect(color)
let add_button = rect(Color::LIME)
.radius(30)
.on(CursorSense::click(), move |mut ctx| {
let (prev, vec) = &mut *vals.borrow_mut();
if let Some(h) = vec[i].take() {
vec[*prev] = ctx[main.r].replace(h);
*prev = i;
}
ctx.widget().color = color.darker(0.3);
let child = ctx.add(image(include_bytes!("assets/sungals.png")).center());
ctx[span_add.r].children.push(child);
})
.on(
CursorSense::HoverStart | CursorSense::unclick(),
move |mut ctx| {
ctx.widget().color = color.brighter(0.2);
},
.sized((150, 150))
.align(Align::BOT_RIGHT);
let del_button = rect(Color::RED)
.radius(30)
.on(CursorSense::click(), move |mut ctx| {
ctx[span_add.r].children.pop();
})
.sized((150, 150))
.align(Align::BOT_LEFT);
let span_add_test = (span_add.h, add_button, del_button).stack().add(ui);
let btext = |content| wtext(content).size(30);
let text_test = (
btext("this is a").align(Align::LEFT),
btext("teeeeeeeest").align(Align::RIGHT),
btext("okkk\nokkkkkk!").align(Align::LEFT),
btext("hmm"),
btext("a"),
(
btext("'").family(Family::Monospace).align(Align::TOP),
btext("'").family(Family::Monospace),
btext(":gamer mode").family(Family::Monospace),
rect(Color::CYAN).sized((10, 10)).center(),
rect(Color::RED).sized((100, 100)).center(),
rect(Color::PURPLE).sized((50, 50)).align(Align::TOP),
)
.on(CursorSense::HoverEnd, move |mut ctx| {
ctx.widget().color = color;
});
(rect, wtext(label).size(30).text_align(Align::CENTER)).stack()
};
.span(Dir::RIGHT)
.center(),
wtext("pretty cool right?").size(50),
)
.span(Dir::DOWN)
.add(ui);
let tabs = (
switch_button(Color::RED, pad_test.h, "pad"),
switch_button(Color::GREEN, span_test, "span"),
switch_button(Color::BLUE, span_add_test, "image span"),
switch_button(Color::MAGENTA, text_test, "text layout"),
switch_button(
Color::YELLOW.mul_rgb(0.5),
text_edit_scroll,
"text edit scroll",
),
)
.span(Dir::RIGHT);
let texts = Span::empty(Dir::DOWN).gap(10).handles(ui);
let msg_area = texts.h.scroll().masked().background(rect(Color::SKY));
let add_text = wtext("add")
.editable(false)
.text_align(Align::LEFT)
.size(30)
.attr::<Selectable>(())
.on(Submit, move |mut ctx| {
let content = ctx.widget.edit(ctx.state.ui()).take();
let text = wtext(content)
.editable(false)
.size(30)
.text_align(Align::LEFT)
.wrap(true)
.attr::<Selectable>(());
let msg_box = text
.background(rect(Color::WHITE.darker(0.5)))
.add(&mut ctx);
ctx[texts.r].children.push(msg_box);
})
.handles(ui);
let text_edit_scroll = (
msg_area.height(rest(1)),
(
Rect::new(Color::WHITE.darker(0.9)),
(
add_text.h.width(rest(1)),
Rect::new(Color::GREEN)
.on(CursorSense::click(), move |ctx| {
ctx.state.run_event::<Submit>(add_text.r, &mut ());
})
.sized((40, 40)),
)
.span(Dir::RIGHT)
.pad(10),
)
.stack()
.size(StackSize::Child(1))
.layer_offset(1)
.align(Align::BOT),
)
.span(Dir::DOWN)
.add(ui);
let info = wtext("").handles(ui);
let info_sect = info.h.pad(10).align(Align::RIGHT);
let main = WidgetPtr::new().handles(ui);
((tabs.height(40), main.h.pad(10)).span(Dir::DOWN), info_sect)
.stack()
.set_root(ui);
let vals = Rc::new(RefCell::new((0, Vec::new())));
let mut switch_button = |color, to: WidgetHandle<Self>, label| {
let vec = &mut vals.borrow_mut().1;
let i = vec.len();
if vec.is_empty() {
vec.push(None);
ui[main.r].set(to);
} else {
vec.push(Some(to));
}
let vals = vals.clone();
let rect = rect(color)
.on(CursorSense::click(), move |mut ctx| {
let (prev, vec) = &mut *vals.borrow_mut();
if let Some(h) = vec[i].take() {
vec[*prev] = ctx[main.r].replace(h);
*prev = i;
}
ctx.widget().color = color.darker(0.3);
})
.on(
CursorSense::HoverStart | CursorSense::unclick(),
move |mut ctx| {
ctx.widget().color = color.brighter(0.2);
},
)
.on(CursorSense::HoverEnd, move |mut ctx| {
ctx.widget().color = color;
});
(rect, wtext(label).size(30).text_align(Align::CENTER)).stack()
};
Self { info: info.r }
let tabs = (
switch_button(Color::RED, pad_test.h, "pad"),
switch_button(Color::GREEN, span_test, "span"),
switch_button(Color::BLUE, span_add_test, "image span"),
switch_button(Color::MAGENTA, text_test, "text layout"),
switch_button(
Color::YELLOW.mul_rgb(0.5),
text_edit_scroll,
"text edit scroll",
),
)
.span(Dir::RIGHT);
info = wtext("").handles(ui);
let info_sect = info.h.pad(10).align(Align::RIGHT);
((tabs.height(40), main.h.pad(10)).span(Dir::DOWN), info_sect)
.stack()
.set_root(ui);
}
Self {
ui,
ui_state: UiState::new(window),
info: info.r,
}
}
fn window_event(&mut self, _: WindowEvent, ui: &mut Ui, state: &UiState) {
fn window_event(&mut self, _: WindowEvent) {
let new = format!(
"widgets: {}\nactive:{}\nviews: {}",
ui.num_widgets(),
ui.active_widgets(),
state.renderer.ui.view_count()
self.ui.num_widgets(),
self.ui.active_widgets(),
self.ui_state.renderer.ui.view_count()
);
if new != *ui[self.info].content {
*ui[self.info].content = new;
if new != *self.ui[self.info].content {
*self.ui[self.info].content = new;
}
if ui.needs_redraw() {
state.window.request_redraw();
if self.ui.needs_redraw() {
self.ui_state.window.request_redraw();
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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