Run, MakeWidget, styles!

This commit is contained in:
Jonathan Johnson 2023-10-27 10:41:13 -07:00
parent 69f6f68ba6
commit 304032f1b0
No known key found for this signature in database
GPG key ID: A66D6A34D6620579
11 changed files with 182 additions and 59 deletions

View file

@ -1,7 +1,6 @@
use gooey::dynamic::Dynamic; use gooey::dynamic::Dynamic;
use gooey::widget::Widget;
use gooey::widgets::Button; use gooey::widgets::Button;
use gooey::EventLoopError; use gooey::{EventLoopError, Run};
fn main() -> Result<(), EventLoopError> { fn main() -> Result<(), EventLoopError> {
let count = Dynamic::new(0_usize); let count = Dynamic::new(0_usize);

View file

@ -1,5 +1,5 @@
use gooey::widget::Widget;
use gooey::widgets::Canvas; use gooey::widgets::Canvas;
use gooey::Run;
use kludgine::figures::units::Px; use kludgine::figures::units::Px;
use kludgine::figures::{Angle, IntoSigned, Point, Rect, Size}; use kludgine::figures::{Angle, IntoSigned, Point, Rect, Size};
use kludgine::shapes::Shape; use kludgine::shapes::Shape;

View file

@ -2,10 +2,9 @@ use std::string::ToString;
use gooey::children::Children; use gooey::children::Children;
use gooey::dynamic::Dynamic; use gooey::dynamic::Dynamic;
use gooey::widget::Widget;
use gooey::widgets::array::Array; use gooey::widgets::array::Array;
use gooey::widgets::{Button, Label}; use gooey::widgets::{Button, Label};
use gooey::EventLoopError; use gooey::{EventLoopError, Run};
fn main() -> Result<(), EventLoopError> { fn main() -> Result<(), EventLoopError> {
let counter = Dynamic::new(0i32); let counter = Dynamic::new(0i32);

View file

@ -1,6 +1,5 @@
use gooey::widget::Widget;
use gooey::widgets::Input; use gooey::widgets::Input;
use gooey::EventLoopError; use gooey::{EventLoopError, Run};
fn main() -> Result<(), EventLoopError> { fn main() -> Result<(), EventLoopError> {
Input::new("Hello").run() Input::new("Hello").run()

View file

@ -4,19 +4,22 @@ use gooey::widget::Widget;
use gooey::widgets::array::Array; use gooey::widgets::array::Array;
use gooey::widgets::{Button, Style}; use gooey::widgets::{Button, Style};
use gooey::window::Window; use gooey::window::Window;
use gooey::EventLoopError; use gooey::{styles, EventLoopError, Run};
use kludgine::Color; use kludgine::Color;
fn main() -> Result<(), EventLoopError> { fn main() -> Result<(), EventLoopError> {
Window::for_widget(Array::rows( Window::for_widget(
Children::new() Array::rows(
.with_widget(Button::new("Default")) Children::new()
.with_widget(styled(Button::new("Styled"))), .with_widget(Button::new("Default"))
)) .with_widget(red_text(Button::new("Styled"))),
.styles(Styles::new().with(&TextColor, Color::GREEN)) )
.with_styles(Styles::new().with(&TextColor, Color::GREEN)),
)
.run() .run()
} }
fn styled(w: impl Widget) -> Style { /// Creating reusable style helpers that work with any Widget is straightfoward
Style::new(Styles::new().with(&TextColor, Color::RED), w) fn red_text(w: impl Widget) -> Style {
Style::new(styles!(TextColor => Color::RED), w)
} }

View file

@ -2,7 +2,7 @@ use std::ops::{Index, IndexMut};
use alot::OrderedLots; use alot::OrderedLots;
use crate::widget::{BoxedWidget, Widget}; use crate::widget::{BoxedWidget, MakeWidget};
#[derive(Debug, Default)] #[derive(Debug, Default)]
#[must_use] #[must_use]
@ -19,9 +19,9 @@ impl Children {
pub fn with_widget<W>(mut self, widget: W) -> Self pub fn with_widget<W>(mut self, widget: W) -> Self
where where
W: Widget, W: MakeWidget,
{ {
self.ordered.push(BoxedWidget::new(widget)); self.ordered.push(widget.make_widget());
self self
} }

View file

@ -17,6 +17,7 @@ pub mod widget;
pub mod widgets; pub mod widgets;
pub mod window; pub mod window;
pub use kludgine;
pub use kludgine::app::winit::error::EventLoopError; pub use kludgine::app::winit::error::EventLoopError;
pub use kludgine::app::winit::event::ElementState; pub use kludgine::app::winit::event::ElementState;
use kludgine::figures::units::UPx; use kludgine::figures::units::UPx;
@ -37,3 +38,7 @@ impl ConstraintLimit {
} }
pub type Result<T, E = EventLoopError> = std::result::Result<T, E>; pub type Result<T, E = EventLoopError> = std::result::Result<T, E>;
pub trait Run: Sized {
fn run(self) -> Result<(), EventLoopError>;
}

View file

@ -1,10 +1,36 @@
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashMap; use std::collections::{hash_map, HashMap};
use std::sync::Arc; use std::sync::Arc;
use crate::names::Name; use crate::names::Name;
use crate::utils::Lazy; use crate::utils::Lazy;
#[macro_export]
#[doc(hidden)]
macro_rules! count {
($value:expr ;) => {
1
};
($value:expr , $($remaining:expr),+ ;) => {
1 + count!($($remaining),+ ;)
}
}
#[macro_export]
macro_rules! styles {
() => {{
$crate::styles::Styles::new()
}};
($($component:expr => $value:expr),*) => {{
let mut styles = $crate::styles::Styles::with_capacity($crate::count!($($value),* ;));
$(styles.push(&$component, $value);)*
styles
}};
($($component:expr => $value:expr),* ,) => {{
$crate::styles!($($component => $value),*)
}};
}
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct Styles(Arc<HashMap<Group, HashMap<Name, Component>>>); pub struct Styles(Arc<HashMap<Group, HashMap<Name, Component>>>);
@ -14,14 +40,23 @@ impl Styles {
Self::default() Self::default()
} }
pub fn push(&mut self, name: &impl NamedComponent, component: impl Into<Component>) { #[must_use]
let name = name.name().into_owned(); pub fn with_capacity(components: usize) -> Self {
Self(Arc::new(HashMap::with_capacity(components)))
}
pub fn push_component(&mut self, name: ComponentName, component: impl Into<Component>) {
Arc::make_mut(&mut self.0) Arc::make_mut(&mut self.0)
.entry(name.group) .entry(name.group)
.or_default() .or_default()
.insert(name.name, component.into()); .insert(name.name, component.into());
} }
pub fn push(&mut self, name: &impl NamedComponent, component: impl Into<Component>) {
let name = name.name().into_owned();
self.push_component(name, component);
}
#[must_use] #[must_use]
pub fn with(mut self, name: &impl NamedComponent, component: impl Into<Component>) -> Self { pub fn with(mut self, name: &impl NamedComponent, component: impl Into<Component>) -> Self {
self.push(name, component); self.push(name, component);
@ -53,6 +88,54 @@ impl Styles {
} }
} }
impl FromIterator<(ComponentName, Component)> for Styles {
fn from_iter<T: IntoIterator<Item = (ComponentName, Component)>>(iter: T) -> Self {
let iter = iter.into_iter();
let mut styles = Self::with_capacity(iter.size_hint().0);
for (name, component) in iter {
styles.push_component(name, component);
}
styles
}
}
impl IntoIterator for Styles {
type IntoIter = StylesIntoIter;
type Item = (ComponentName, Component);
fn into_iter(self) -> Self::IntoIter {
StylesIntoIter {
main: Arc::try_unwrap(self.0)
.unwrap_or_else(|err| err.as_ref().clone())
.into_iter(),
names: None,
}
}
}
pub struct StylesIntoIter {
main: hash_map::IntoIter<Group, HashMap<Name, Component>>,
names: Option<(Group, hash_map::IntoIter<Name, Component>)>,
}
impl Iterator for StylesIntoIter {
type Item = (ComponentName, Component);
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some((group, names)) = &mut self.names {
if let Some((name, component)) = names.next() {
return Some((ComponentName::new(group.clone(), name), component));
}
self.names = None;
}
let (group, names) = self.main.next()?;
self.names = Some((group, names.into_iter()));
}
}
}
pub type StyleQuery = Vec<ComponentName>; pub type StyleQuery = Vec<ComponentName>;
use std::any::Any; use std::any::Any;
use std::fmt::Debug; use std::fmt::Debug;

View file

@ -15,17 +15,11 @@ use crate::context::{EventContext, GraphicsContext};
use crate::dynamic::Dynamic; use crate::dynamic::Dynamic;
use crate::styles::{Component, Group, Styles}; use crate::styles::{Component, Group, Styles};
use crate::tree::{Tree, WidgetId}; use crate::tree::{Tree, WidgetId};
use crate::widgets::Style;
use crate::window::{RunningWindow, Window, WindowBehavior}; use crate::window::{RunningWindow, Window, WindowBehavior};
use crate::ConstraintLimit; use crate::{ConstraintLimit, Run};
pub trait Widget: Send + UnwindSafe + Debug + 'static { pub trait Widget: Send + UnwindSafe + Debug + 'static {
fn run(self) -> Result<(), EventLoopError>
where
Self: Sized,
{
Window::<BoxedWidget>::new(BoxedWidget::new(self)).run()
}
fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_, '_>); fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_, '_>);
fn measure( fn measure(
@ -123,6 +117,39 @@ pub trait Widget: Send + UnwindSafe + Debug + 'static {
fn query_component(&self, group: Group, name: &str) -> Option<Component> { fn query_component(&self, group: Group, name: &str) -> Option<Component> {
None None
} }
fn with_styles(self, styles: impl Into<Styles>) -> Style
where
Self: Sized,
{
Style::new(styles, self)
}
}
impl<T> Run for T
where
T: Widget,
{
fn run(self) -> crate::Result<(), EventLoopError> {
BoxedWidget::new(self).run()
}
}
pub trait MakeWidget: Sized {
fn make_widget(self) -> BoxedWidget;
fn run(self) -> Result<(), EventLoopError> {
self.make_widget().run()
}
}
impl<T> MakeWidget for T
where
T: Widget,
{
fn make_widget(self) -> BoxedWidget {
BoxedWidget::new(self)
}
} }
pub type EventHandling = ControlFlow<EventHandled, EventIgnored>; pub type EventHandling = ControlFlow<EventHandled, EventIgnored>;
@ -151,6 +178,12 @@ impl BoxedWidget {
} }
} }
impl Run for BoxedWidget {
fn run(self) -> crate::Result<(), EventLoopError> {
Window::<BoxedWidget>::new(self).run()
}
}
impl Eq for BoxedWidget {} impl Eq for BoxedWidget {}
impl PartialEq for BoxedWidget { impl PartialEq for BoxedWidget {
@ -172,25 +205,30 @@ impl WindowBehavior for BoxedWidget {
} }
#[derive(Debug)] #[derive(Debug)]
pub enum Value<T> pub enum Value<T> {
where Constant(T),
T: 'static,
{
Static(T),
Dynamic(Dynamic<T>), Dynamic(Dynamic<T>),
} }
impl<T> Value<T> { impl<T> Value<T> {
pub fn dynamic(value: T) -> Self {
Self::Dynamic(Dynamic::new(value))
}
pub fn constant(value: T) -> Self {
Self::Constant(value)
}
pub fn map<R>(&mut self, map: impl FnOnce(&T) -> R) -> R { pub fn map<R>(&mut self, map: impl FnOnce(&T) -> R) -> R {
match self { match self {
Value::Static(value) => map(value), Value::Constant(value) => map(value),
Value::Dynamic(dynamic) => dynamic.map_ref(map), Value::Dynamic(dynamic) => dynamic.map_ref(map),
} }
} }
pub fn map_mut<R>(&mut self, map: impl FnOnce(&mut T) -> R) -> R { pub fn map_mut<R>(&mut self, map: impl FnOnce(&mut T) -> R) -> R {
match self { match self {
Value::Static(value) => map(value), Value::Constant(value) => map(value),
Value::Dynamic(dynamic) => dynamic.map_mut(map), Value::Dynamic(dynamic) => dynamic.map_mut(map),
} }
} }
@ -204,7 +242,7 @@ impl<T> Value<T> {
pub fn generation(&self) -> Option<usize> { pub fn generation(&self) -> Option<usize> {
match self { match self {
Value::Static(_) => None, Value::Constant(_) => None,
Value::Dynamic(value) => Some(value.generation()), Value::Dynamic(value) => Some(value.generation()),
} }
} }
@ -216,13 +254,13 @@ pub trait IntoValue<T> {
impl<T> IntoValue<T> for T { impl<T> IntoValue<T> for T {
fn into_value(self) -> Value<T> { fn into_value(self) -> Value<T> {
Value::Static(self) Value::Constant(self)
} }
} }
impl<'a> IntoValue<String> for &'a str { impl<'a> IntoValue<String> for &'a str {
fn into_value(self) -> Value<String> { fn into_value(self) -> Value<String> {
Value::Static(self.to_owned()) Value::Constant(self.to_owned())
} }
} }
@ -232,6 +270,12 @@ impl<T> IntoValue<T> for Dynamic<T> {
} }
} }
impl<T> IntoValue<T> for Value<T> {
fn into_value(self) -> Value<T> {
self
}
}
pub struct Callback<T>(Box<dyn CallbackFunction<T>>); pub struct Callback<T>(Box<dyn CallbackFunction<T>>);
impl<T> Debug for Callback<T> { impl<T> Debug for Callback<T> {

View file

@ -14,12 +14,9 @@ pub struct Style {
} }
impl Style { impl Style {
pub fn new<W>(styles: Styles, child: W) -> Self pub fn new(styles: impl Into<Styles>, child: impl Widget) -> Self {
where
W: Widget,
{
Self { Self {
styles, styles: styles.into(),
child: BoxedWidget::new(child), child: BoxedWidget::new(child),
mounted_child: None, mounted_child: None,
} }

View file

@ -16,11 +16,11 @@ use kludgine::Kludgine;
use crate::context::{EventContext, Exclusive, GraphicsContext, WidgetContext}; use crate::context::{EventContext, Exclusive, GraphicsContext, WidgetContext};
use crate::graphics::Graphics; use crate::graphics::Graphics;
use crate::styles::Styles;
use crate::tree::Tree; use crate::tree::Tree;
use crate::utils::ModifiersExt; use crate::utils::ModifiersExt;
use crate::widget::{BoxedWidget, EventHandling, ManagedWidget, Widget, HANDLED, UNHANDLED}; use crate::widget::{BoxedWidget, EventHandling, ManagedWidget, Widget, HANDLED, UNHANDLED};
use crate::window::sealed::WindowCommand; use crate::window::sealed::WindowCommand;
use crate::Run;
pub type RunningWindow<'window> = kludgine::app::Window<'window, WindowCommand>; pub type RunningWindow<'window> = kludgine::app::Window<'window, WindowCommand>;
pub type WindowAttributes = kludgine::app::WindowAttributes<WindowCommand>; pub type WindowAttributes = kludgine::app::WindowAttributes<WindowCommand>;
@ -32,7 +32,6 @@ where
{ {
context: Behavior::Context, context: Behavior::Context,
pub attributes: WindowAttributes, pub attributes: WindowAttributes,
pub styles: Option<Styles>,
} }
impl<Behavior> Default for Window<Behavior> impl<Behavior> Default for Window<Behavior>
@ -66,20 +65,18 @@ where
..WindowAttributes::default() ..WindowAttributes::default()
}, },
context, context,
styles: None,
} }
} }
}
pub fn styles(mut self, styles: Styles) -> Self { impl<Behavior> Run for Window<Behavior>
self.styles = Some(styles); where
self Behavior: WindowBehavior,
} {
fn run(self) -> crate::Result<(), EventLoopError> {
pub fn run(self) -> Result<(), EventLoopError> {
GooeyWindow::<Behavior>::run_with(AssertUnwindSafe(( GooeyWindow::<Behavior>::run_with(AssertUnwindSafe((
self.context, self.context,
RefCell::new(WindowSettings { RefCell::new(WindowSettings {
styles: self.styles,
attributes: Some(self.attributes), attributes: Some(self.attributes),
}), }),
))) )))
@ -142,9 +139,7 @@ where
) -> Self { ) -> Self {
let mut behavior = T::initialize(&mut window, context.0 .0); let mut behavior = T::initialize(&mut window, context.0 .0);
let root = Tree::default().push_boxed(behavior.make_root(), None); let root = Tree::default().push_boxed(behavior.make_root(), None);
if let Some(styles) = context.0 .1.borrow_mut().styles.take() {
root.attach_styles(styles);
}
Self { Self {
behavior, behavior,
root, root,
@ -425,7 +420,6 @@ fn recursively_handle_event(
} }
pub struct WindowSettings { pub struct WindowSettings {
styles: Option<Styles>,
attributes: Option<WindowAttributes>, attributes: Option<WindowAttributes>,
} }