Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
506ccae049 | ||
|
|
86e3f4e684 | ||
|
|
89b460697f | ||
|
|
bd53e6450c | ||
|
|
083812458b | ||
|
|
4364177538 | ||
|
|
98598bec15 | ||
|
|
eb702dce45 | ||
|
|
229353f5f0 | ||
|
|
04a69b138a | ||
|
|
993a790da7 | ||
|
|
ecc1172737 | ||
|
|
a9ecc8da8b | ||
|
|
f6a4bbd8ac | ||
|
|
4afe1c24c2 | ||
|
|
b50ca3263b | ||
|
|
6b3e9239c9 | ||
|
|
470512a542 | ||
|
|
6e481862ec | ||
|
|
05a390b10f | ||
|
|
926405a863 | ||
|
|
9953e4a0bc | ||
|
|
8f0712d4f8 | ||
|
|
9d55dacde2 | ||
|
|
abe37686d8 | ||
|
|
02f3aea4e3 | ||
|
|
33370287b2 | ||
|
|
0f12a371e5 | ||
|
|
1f9bf48bb4 | ||
|
|
49bb99fedb | ||
|
|
979af999e4 | ||
|
|
0515087f0d | ||
|
|
2a62e53ed5 | ||
|
|
c2b9bb3aa1 | ||
|
|
0a026c4ee7 | ||
|
|
15ff801cb0 | ||
|
|
538cc8731f | ||
|
|
b326fc48ed | ||
|
|
8740bbee89 | ||
|
|
22d02e7d1a | ||
|
|
0cefbaa223 | ||
|
|
b57fffe9b7 | ||
|
|
4d2f0d7b9d | ||
|
|
ff351caee0 | ||
|
|
e4110976cd | ||
|
|
1fbff7a0bc | ||
|
|
6e8ca5535e | ||
|
|
e031f9bcef | ||
|
|
c6d11315d6 | ||
|
|
68d00be96c | ||
|
|
f5d1b42db4 | ||
|
|
63ed7b8da4 | ||
|
|
98b2a4e667 | ||
|
|
e4b905d085 | ||
|
|
1d6ce1506e | ||
|
|
0e3c1ccafe | ||
|
|
dbd16956dd | ||
|
|
c91a473263 | ||
|
|
6424ad3390 | ||
|
|
23edb6c917 | ||
|
|
72e8df007e | ||
|
|
a2350f10f5 | ||
|
|
2d41f3b50b | ||
|
|
5cb6d341af | ||
|
|
f41a4936f9 | ||
|
|
dbb8a0e01a | ||
|
|
fd8e466830 | ||
|
|
29432a939b | ||
|
|
9d4b247b2a | ||
|
|
916818f915 | ||
|
|
5cf59f751d | ||
|
|
c460e073a7 | ||
|
|
f51182b2b1 | ||
|
|
6100023a2a | ||
|
|
3d9aa35964 | ||
|
|
9a03f241d8 | ||
|
|
fde8ad17d6 | ||
|
|
e0cf149790 | ||
|
|
1e590597f3 | ||
|
|
935f18178e | ||
|
|
20a9d2b216 | ||
|
|
3520369e35 | ||
|
|
c8ebe36d78 | ||
|
|
d3861909e7 | ||
|
|
1bdbc447ab | ||
|
|
e0059585ce | ||
|
|
b363c81a24 | ||
|
|
2fae5c71f8 | ||
|
|
9868f02c33 | ||
|
|
896dfb0a36 | ||
|
|
3a5286a54f | ||
|
|
ca4ee54e9d | ||
|
|
62e0c1eac1 | ||
|
|
48397c06fa | ||
|
|
14602f95c8 | ||
|
|
fbd84f98d3 | ||
|
|
db1de03fbb |
+2
-3
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "osui"
|
name = "osui"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "A TUI library for advanced uis"
|
description = "A TUI library for advanced uis"
|
||||||
@@ -9,8 +9,7 @@ homepage = "https://osui.netlify.app"
|
|||||||
documentation = "https://osui.netlify.app/docs/"
|
documentation = "https://osui.netlify.app/docs/"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
no_rsx = []
|
rsx = []
|
||||||
no_elem = []
|
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "osui"
|
name = "osui"
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use osui::{prelude::*, rsx};
|
||||||
|
|
||||||
|
pub struct Count(pub State<u16>);
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let console = Console::new();
|
||||||
|
console.run(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn app(cx: &Arc<Context>) -> View {
|
||||||
|
let count = use_state(0);
|
||||||
|
let mount = use_mount_manual();
|
||||||
|
|
||||||
|
// Sync state with children
|
||||||
|
use_sync_effect(cx, &count, |v| Count(v.clone()), &[&mount, &count]);
|
||||||
|
|
||||||
|
use_effect(
|
||||||
|
{
|
||||||
|
let count = count.clone();
|
||||||
|
move || loop {
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||||
|
let mut count = count.get();
|
||||||
|
if *count > 5 {
|
||||||
|
*count = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
*count += 1;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
&[&mount],
|
||||||
|
);
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
// Static scope
|
||||||
|
my_component (ctx, view) {
|
||||||
|
let area = ctx.allocate(5, 0, 10, 10);
|
||||||
|
ctx.draw_view(area, view);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dynamic scope
|
||||||
|
if %count (*count.get() > 5) {
|
||||||
|
my_component (ctx, view) {
|
||||||
|
let area = ctx.allocate(18, 0, 10, 10);
|
||||||
|
ctx.draw_view(area, view);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dynamic scope
|
||||||
|
for %count (i in 0..count.get_dl()) {
|
||||||
|
"{i}" @Point { x: 0, y: i };
|
||||||
|
}
|
||||||
|
|
||||||
|
!mount mount
|
||||||
|
}
|
||||||
|
.view(cx.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn my_component(cx: &Arc<Context>) -> View {
|
||||||
|
// Sync state with parent
|
||||||
|
let count = use_sync_state(cx, 0, |Count(v)| v.get_dl());
|
||||||
|
|
||||||
|
rsx! {
|
||||||
|
"Count: {count}"
|
||||||
|
}
|
||||||
|
.view(cx.clone())
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
use std::{
|
||||||
|
any::{Any, TypeId},
|
||||||
|
collections::HashMap,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
render::DrawContext,
|
||||||
|
state::{use_effect, HookDependency},
|
||||||
|
View, ViewWrapper,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub type Component = Arc<dyn Fn(&Arc<Context>) -> View + Send + Sync>;
|
||||||
|
pub type EventHandler = Arc<Mutex<dyn FnMut(&Arc<Context>, &dyn Any) + Send + Sync>>;
|
||||||
|
|
||||||
|
pub struct Scope {
|
||||||
|
pub children: Mutex<Vec<(Arc<Context>, Option<ViewWrapper>)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Context {
|
||||||
|
component: Mutex<Component>,
|
||||||
|
event_handlers: Mutex<HashMap<TypeId, Vec<EventHandler>>>,
|
||||||
|
view: Mutex<View>,
|
||||||
|
pub(crate) scopes: Mutex<Vec<Arc<Scope>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Context {
|
||||||
|
pub fn new<F: Fn(&Arc<Self>) -> View + Send + Sync + 'static>(component: F) -> Arc<Self> {
|
||||||
|
Arc::new(Self {
|
||||||
|
component: Mutex::new(Arc::new(component)),
|
||||||
|
event_handlers: Mutex::new(HashMap::new()),
|
||||||
|
view: Mutex::new(Arc::new(|_| {})),
|
||||||
|
scopes: Mutex::new(Vec::new()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh(self: &Arc<Self>) {
|
||||||
|
let s = self.clone();
|
||||||
|
|
||||||
|
std::thread::spawn({
|
||||||
|
move || {
|
||||||
|
s.event_handlers.lock().unwrap().clear();
|
||||||
|
let c = s.component.lock().unwrap().clone();
|
||||||
|
*s.view.lock().unwrap() = (c)(&s);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh_atomic(self: &Arc<Self>) -> Arc<Mutex<bool>> {
|
||||||
|
let s = self.clone();
|
||||||
|
let done = Arc::new(Mutex::new(false));
|
||||||
|
|
||||||
|
std::thread::spawn({
|
||||||
|
let done = done.clone();
|
||||||
|
move || {
|
||||||
|
s.event_handlers.lock().unwrap().clear();
|
||||||
|
let c = s.component.lock().unwrap().clone();
|
||||||
|
*s.view.lock().unwrap() = (c)(&s);
|
||||||
|
*done.lock().unwrap() = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_view(self: &Arc<Self>) -> View {
|
||||||
|
self.view.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_event<T: Any + 'static, F: Fn(&Arc<Self>, &T) + Send + Sync + 'static>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
handler: F,
|
||||||
|
) {
|
||||||
|
self.event_handlers
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.entry(TypeId::of::<T>())
|
||||||
|
.or_insert_with(|| Vec::new())
|
||||||
|
.push(Arc::new(Mutex::new(
|
||||||
|
move |ctx: &Arc<Self>, event: &dyn Any| {
|
||||||
|
if let Some(e) = event.downcast_ref::<T>() {
|
||||||
|
(handler)(ctx, e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn emit_event<E: Any + 'static>(self: &Arc<Self>, event: &E) {
|
||||||
|
if let Some(v) = self.event_handlers.lock().unwrap().get(&TypeId::of::<E>()) {
|
||||||
|
for i in v {
|
||||||
|
(i.lock().unwrap())(self, event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for scope in self.scopes.lock().unwrap().iter() {
|
||||||
|
for (child, _) in scope.children.lock().unwrap().iter() {
|
||||||
|
child.emit_event(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn emit_event_threaded<E: Any + Send + Sync + Clone + 'static>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
event: &E,
|
||||||
|
) {
|
||||||
|
if let Some(v) = self.event_handlers.lock().unwrap().get(&TypeId::of::<E>()) {
|
||||||
|
for i in v {
|
||||||
|
let i = i.clone();
|
||||||
|
let event = event.clone();
|
||||||
|
let s = self.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
(i.lock().unwrap())(&s, &event);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for scope in self.scopes.lock().unwrap().iter() {
|
||||||
|
for (child, _) in scope.children.lock().unwrap().iter() {
|
||||||
|
child.emit_event_threaded(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scope(self: &Arc<Self>) -> Arc<Scope> {
|
||||||
|
let scope = Arc::new(Scope {
|
||||||
|
children: Mutex::new(Vec::new()),
|
||||||
|
});
|
||||||
|
self.scopes.lock().unwrap().push(scope.clone());
|
||||||
|
|
||||||
|
scope
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dyn_scope<F: Fn(&Arc<Scope>) + Send + Sync + 'static>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
drawer: F,
|
||||||
|
dependencies: &[&dyn HookDependency],
|
||||||
|
) -> Arc<Scope> {
|
||||||
|
let scope = Arc::new(Scope {
|
||||||
|
children: Mutex::new(Vec::new()),
|
||||||
|
});
|
||||||
|
self.scopes.lock().unwrap().push(scope.clone());
|
||||||
|
|
||||||
|
drawer(&scope);
|
||||||
|
|
||||||
|
use_effect(
|
||||||
|
{
|
||||||
|
let scope = scope.clone();
|
||||||
|
move || {
|
||||||
|
drawer(&scope);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dependencies,
|
||||||
|
);
|
||||||
|
|
||||||
|
scope
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_children(self: &Arc<Self>, ctx: &mut DrawContext) {
|
||||||
|
for scope in self.scopes.lock().unwrap().iter() {
|
||||||
|
for (child, view_wrapper) in scope.children.lock().unwrap().iter() {
|
||||||
|
let view = child.get_view();
|
||||||
|
|
||||||
|
if let Some(view_wrapper) = view_wrapper {
|
||||||
|
view_wrapper(ctx, view)
|
||||||
|
} else {
|
||||||
|
ctx.draw_view(ctx.area.clone(), view);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scope {
|
||||||
|
pub fn new() -> Arc<Self> {
|
||||||
|
Arc::new(Self {
|
||||||
|
children: Mutex::new(Vec::new()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn child<F: Fn(&Arc<Context>) -> View + Send + Sync + 'static>(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
child: F,
|
||||||
|
view_wrapper: Option<ViewWrapper>,
|
||||||
|
) {
|
||||||
|
let ctx = Context::new(child);
|
||||||
|
|
||||||
|
ctx.refresh();
|
||||||
|
|
||||||
|
self.children.lock().unwrap().push((ctx, view_wrapper));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view(self: &Arc<Self>, view: View) {
|
||||||
|
let ctx = Context::new(move |_| view.clone());
|
||||||
|
|
||||||
|
ctx.refresh();
|
||||||
|
|
||||||
|
self.children.lock().unwrap().push((ctx, None));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use osui::prelude::*;
|
|
||||||
|
|
||||||
pub fn app(screen: Arc<Screen>) -> Rsx {
|
|
||||||
let count = use_state(0);
|
|
||||||
|
|
||||||
std::thread::spawn({
|
|
||||||
let count = count.clone();
|
|
||||||
move || loop {
|
|
||||||
**count.get() += 1;
|
|
||||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
rsx! {
|
|
||||||
@Handler::new({
|
|
||||||
let screen = screen.clone();
|
|
||||||
move |_, e: &crossterm::event::Event| {
|
|
||||||
if let crossterm::event::Event::Key(crossterm::event::KeyEvent { code, .. }) = e {
|
|
||||||
if *code == crossterm::event::KeyCode::Char('q') {
|
|
||||||
screen.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}});
|
|
||||||
Paginator {
|
|
||||||
FlexRow {
|
|
||||||
Heading, smooth: false, { "OSUI" }
|
|
||||||
"Welcome to the OSUI demo!"
|
|
||||||
"Press tab to switch to the next page or shift+tab to the previous page"
|
|
||||||
}
|
|
||||||
|
|
||||||
FlexCol, gap: 3, {
|
|
||||||
@Transform::new().padding(2, 2);
|
|
||||||
@Style { foreground: None, background: Background::RoundedOutline(0x00ff00) };
|
|
||||||
Div {
|
|
||||||
"This is text inside a div"
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transform::new().padding(2, 2);
|
|
||||||
@Style { foreground: None, background: Background::Outline(0x00ff00) };
|
|
||||||
Div {
|
|
||||||
"This is text inside a div with square outlines"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: div with width full
|
|
||||||
}
|
|
||||||
|
|
||||||
FlexCol, gap: 2, {
|
|
||||||
@transform!{ y: Center };
|
|
||||||
static Div { // static only affects the element, not children
|
|
||||||
%count
|
|
||||||
"This will increment every second: {count}"
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transform::new().padding(1, 1).dimensions(40, 1);
|
|
||||||
@Style { foreground: Some(0xffffff), background: Background::RoundedOutline(0xff0000) };
|
|
||||||
Input { }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
widget::{Element, Widget},
|
|
||||||
NoRender, NoRenderRoot,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Div {
|
|
||||||
children: Vec<Arc<Widget>>,
|
|
||||||
size: (u16, u16),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Div {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Div {
|
|
||||||
children: Vec::new(),
|
|
||||||
size: (0, 0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for Div {
|
|
||||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
|
||||||
scope.use_area(width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
let mut transform = scope.get_transform().clone();
|
|
||||||
let (w, h) = scope.get_parent_size();
|
|
||||||
scope.set_parent_size(transform.width, transform.height);
|
|
||||||
|
|
||||||
for elem in &self.children {
|
|
||||||
if elem.get::<NoRender>().is_some() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
scope.clear();
|
|
||||||
|
|
||||||
if let Some(style) = elem.get() {
|
|
||||||
scope.set_style(style);
|
|
||||||
}
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
elem.get_elem().render(scope);
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
let t = scope.get_transform_mut();
|
|
||||||
transform.width = transform.width.max(t.x + t.width + (t.px * 2));
|
|
||||||
transform.height = transform.height.max(t.y + t.height + (t.py * 2));
|
|
||||||
t.x += transform.x + transform.px;
|
|
||||||
t.y += transform.y + transform.py;
|
|
||||||
|
|
||||||
scope.draw();
|
|
||||||
elem.get_elem().after_render(scope);
|
|
||||||
}
|
|
||||||
scope.set_parent_size(w, h);
|
|
||||||
self.size = (transform.width, transform.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_child(&mut self, element: &Arc<Widget>) {
|
|
||||||
self.children.push(element.clone());
|
|
||||||
element.inject(|w| w.component(NoRenderRoot));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
widget::{Element, Widget},
|
|
||||||
NoRender, NoRenderRoot,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct FlexRow {
|
|
||||||
pub gap: u16,
|
|
||||||
children: Vec<Arc<Widget>>,
|
|
||||||
size: (u16, u16),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct FlexCol {
|
|
||||||
pub gap: u16,
|
|
||||||
children: Vec<Arc<Widget>>,
|
|
||||||
size: (u16, u16),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FlexRow {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
children: Vec::new(),
|
|
||||||
size: (0, 0),
|
|
||||||
gap: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FlexCol {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
children: Vec::new(),
|
|
||||||
size: (0, 0),
|
|
||||||
gap: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for FlexRow {
|
|
||||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
|
||||||
scope.use_area(width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
let mut transform = scope.get_transform().clone();
|
|
||||||
let (w, h) = scope.get_parent_size();
|
|
||||||
scope.set_parent_size(transform.width, transform.height);
|
|
||||||
|
|
||||||
let mut v = 0;
|
|
||||||
|
|
||||||
for elem in &self.children {
|
|
||||||
if elem.get::<NoRender>().is_some() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
scope.clear();
|
|
||||||
if let Some(style) = elem.get() {
|
|
||||||
scope.set_style(style);
|
|
||||||
}
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
elem.get_elem().render(scope);
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
let t = scope.get_transform_mut();
|
|
||||||
transform.width = transform.width.max(t.width);
|
|
||||||
transform.height = transform.height.max(v + t.height);
|
|
||||||
t.x += transform.x;
|
|
||||||
t.y += transform.y + v;
|
|
||||||
v += t.height + self.gap + (t.py * 2);
|
|
||||||
t.px += transform.px;
|
|
||||||
t.py += transform.py;
|
|
||||||
|
|
||||||
scope.draw();
|
|
||||||
|
|
||||||
elem.get_elem().after_render(scope);
|
|
||||||
}
|
|
||||||
scope.set_parent_size(w, h);
|
|
||||||
self.size = (transform.width, transform.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_child(&mut self, element: &Arc<Widget>) {
|
|
||||||
self.children.push(element.clone());
|
|
||||||
element.inject(|w| w.component(NoRenderRoot));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for FlexCol {
|
|
||||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
|
||||||
scope.use_area(width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
let mut transform = scope.get_transform().clone();
|
|
||||||
let (w, h) = scope.get_parent_size();
|
|
||||||
scope.set_parent_size(transform.width, transform.height);
|
|
||||||
|
|
||||||
let mut v = 0;
|
|
||||||
|
|
||||||
for elem in &self.children {
|
|
||||||
if elem.get::<NoRender>().is_some() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
scope.clear();
|
|
||||||
if let Some(style) = elem.get() {
|
|
||||||
scope.set_style(style);
|
|
||||||
}
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
elem.get_elem().render(scope);
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
let t = scope.get_transform_mut();
|
|
||||||
transform.width = transform.width.max(v + t.width + (t.px * 2));
|
|
||||||
transform.height = transform.height.max(t.height + (t.py * 2));
|
|
||||||
t.x += transform.x + v;
|
|
||||||
t.y += transform.y;
|
|
||||||
v += t.width + self.gap + (t.px * 2);
|
|
||||||
t.px += transform.px;
|
|
||||||
t.py += transform.py;
|
|
||||||
|
|
||||||
scope.draw();
|
|
||||||
|
|
||||||
elem.get_elem().after_render(scope);
|
|
||||||
}
|
|
||||||
scope.set_parent_size(w, h);
|
|
||||||
self.size = (transform.width, transform.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_child(&mut self, element: &Arc<Widget>) {
|
|
||||||
self.children.push(element.clone());
|
|
||||||
element.inject(|w| w.component(NoRenderRoot));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use figlet_rs::FIGfont;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
widget::{Element, Widget},
|
|
||||||
NoRender, NoRenderRoot,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Heading {
|
|
||||||
pub font: FIGfont,
|
|
||||||
pub smooth: bool,
|
|
||||||
children: Vec<Arc<Widget>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Heading {
|
|
||||||
pub fn new() -> Heading {
|
|
||||||
Heading {
|
|
||||||
font: FIGfont::standard().unwrap(),
|
|
||||||
smooth: false,
|
|
||||||
children: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for Heading {
|
|
||||||
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
|
|
||||||
let mut s = String::new();
|
|
||||||
for element in &self.children {
|
|
||||||
if element.get::<NoRender>().is_some() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(e) = element.get_elem().as_any().downcast_ref::<String>() {
|
|
||||||
s += e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(t) = self.font.convert(&s) {
|
|
||||||
scope.draw_text(
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
&if self.smooth {
|
|
||||||
format!("{t}").replace("-", "─").replace("|", "│")
|
|
||||||
} else {
|
|
||||||
format!("{t}")
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_child(&mut self, element: &Arc<Widget>) {
|
|
||||||
element.inject(|w| w.component(NoRenderRoot));
|
|
||||||
self.children.push(element.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
state::{use_state, State},
|
|
||||||
widget::Element,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Input {
|
|
||||||
pub state: State<String>,
|
|
||||||
cursor: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for Input {
|
|
||||||
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
|
|
||||||
let s = self.state.get();
|
|
||||||
scope.draw_text(0, 0, &s);
|
|
||||||
if let Some(c) = s.chars().nth(self.cursor) {
|
|
||||||
scope.draw_text_inverted(self.cursor as u16, 0, &c.to_string());
|
|
||||||
} else {
|
|
||||||
scope.draw_text_inverted(s.len() as u16, 0, " ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn event(&mut self, event: &dyn crate::prelude::Event) {
|
|
||||||
if let Some(crossterm::event::Event::Key(KeyEvent {
|
|
||||||
code, modifiers, ..
|
|
||||||
})) = event.get()
|
|
||||||
{
|
|
||||||
if !modifiers.is_empty() && !modifiers.contains(KeyModifiers::SHIFT) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
match code {
|
|
||||||
KeyCode::Char(c) => {
|
|
||||||
self.state.get().insert(self.cursor, *c);
|
|
||||||
self.cursor += 1;
|
|
||||||
}
|
|
||||||
KeyCode::Backspace => {
|
|
||||||
if self.cursor > 0 {
|
|
||||||
self.state.get().remove(self.cursor - 1);
|
|
||||||
self.cursor -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Delete => {
|
|
||||||
if self.cursor > 0 && self.state.get().len() > self.cursor {
|
|
||||||
self.state.get().remove(self.cursor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Left => {
|
|
||||||
if self.cursor > 0 {
|
|
||||||
self.cursor -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::Right => {
|
|
||||||
if self.cursor < self.state.get().len() {
|
|
||||||
self.cursor += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Input {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
state: use_state(String::new()),
|
|
||||||
cursor: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
pub mod div;
|
|
||||||
pub mod flex;
|
|
||||||
pub mod heading;
|
|
||||||
pub mod input;
|
|
||||||
pub mod paginator;
|
|
||||||
|
|
||||||
pub use div::*;
|
|
||||||
pub use flex::*;
|
|
||||||
pub use heading::*;
|
|
||||||
pub use input::*;
|
|
||||||
pub use paginator::*;
|
|
||||||
|
|
||||||
use crate::Element;
|
|
||||||
|
|
||||||
impl Element for String {
|
|
||||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
scope.draw_text(0, 0, self);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for (String, u32) {
|
|
||||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
scope.draw_text_colored(0, 0, &self.0, self.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crossterm::event::{KeyCode, KeyEvent};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
widget::{Element, Widget},
|
|
||||||
NoRender, NoRenderRoot,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Paginator {
|
|
||||||
children: Vec<Arc<Widget>>,
|
|
||||||
size: (u16, u16),
|
|
||||||
index: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Paginator {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
children: Vec::new(),
|
|
||||||
size: (0, 0),
|
|
||||||
index: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for Paginator {
|
|
||||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
|
||||||
scope.use_area(width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
|
||||||
if let Some(elem) = self.children.get(self.index) {
|
|
||||||
if elem.get::<NoRender>().is_some() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut transform = scope.get_transform().clone();
|
|
||||||
let (w, h) = scope.get_parent_size();
|
|
||||||
scope.set_parent_size(transform.width, transform.height);
|
|
||||||
scope.clear();
|
|
||||||
|
|
||||||
if let Some(style) = elem.get() {
|
|
||||||
scope.set_style(style);
|
|
||||||
}
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
elem.get_elem().render(scope);
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
let t = scope.get_transform_mut();
|
|
||||||
transform.width = transform.width.max(t.x + t.width + (t.px * 2));
|
|
||||||
transform.height = transform.height.max(t.y + t.height + (t.py * 2));
|
|
||||||
t.x += transform.x + transform.px;
|
|
||||||
t.y += transform.y + transform.py;
|
|
||||||
|
|
||||||
scope.draw();
|
|
||||||
elem.get_elem().after_render(scope);
|
|
||||||
|
|
||||||
scope.set_parent_size(w, h);
|
|
||||||
self.size = (transform.width, transform.height);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn event(&mut self, event: &dyn crate::prelude::Event) {
|
|
||||||
if let Some(crossterm::event::Event::Key(KeyEvent { code, .. })) = event.get() {
|
|
||||||
let cl = self.children.len();
|
|
||||||
match code {
|
|
||||||
KeyCode::Tab => {
|
|
||||||
if self.index + 1 < cl {
|
|
||||||
self.index += 1;
|
|
||||||
} else {
|
|
||||||
self.index = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
KeyCode::BackTab => {
|
|
||||||
if self.index > 0 {
|
|
||||||
self.index -= 1;
|
|
||||||
} else if cl > 0 {
|
|
||||||
self.index = cl - 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw_child(&mut self, element: &Arc<Widget>) {
|
|
||||||
self.children.push(element.clone());
|
|
||||||
element.inject(|w| w.component(NoRenderRoot));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
use std::{
|
||||||
|
io::{stdout, Write},
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crossterm::{cursor::MoveTo, execute, terminal::Clear};
|
||||||
|
|
||||||
|
use crate::{prelude::Context, render::Area, DrawContext, View};
|
||||||
|
|
||||||
|
pub trait Engine {
|
||||||
|
fn render_view(&self, area: &Area, view: &View) -> DrawContext;
|
||||||
|
fn draw_context(&self, ctx: &DrawContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Console {
|
||||||
|
threads: Mutex<Vec<Arc<dyn Fn(Arc<Context>) + Send + Sync>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Console {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
threads: Mutex::new(Vec::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn thread<F: Fn(Arc<Context>) + Send + Sync + 'static>(&self, run: F) {
|
||||||
|
self.threads.lock().unwrap().push(Arc::new(run));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run<F: Fn(&Arc<Context>) -> View + Send + Sync + 'static>(&self, component: F) {
|
||||||
|
let cx = Context::new(component);
|
||||||
|
cx.refresh();
|
||||||
|
|
||||||
|
for thread in self.threads.lock().unwrap().iter() {
|
||||||
|
let thread = thread.clone();
|
||||||
|
|
||||||
|
std::thread::spawn({
|
||||||
|
let cx = cx.clone();
|
||||||
|
move || thread(cx)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let (width, height) = crossterm::terminal::size().unwrap();
|
||||||
|
|
||||||
|
execute!(stdout(), Clear(crossterm::terminal::ClearType::Purge)).unwrap();
|
||||||
|
execute!(stdout(), Clear(crossterm::terminal::ClearType::All)).unwrap();
|
||||||
|
|
||||||
|
self.draw_context(&self.render_view(
|
||||||
|
&Area {
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
},
|
||||||
|
&cx.get_view(),
|
||||||
|
));
|
||||||
|
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(16));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Engine for Console {
|
||||||
|
fn render_view(&self, area: &Area, view: &View) -> DrawContext {
|
||||||
|
let mut context = DrawContext::new(area.clone());
|
||||||
|
view(&mut context);
|
||||||
|
context
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_context(&self, ctx: &DrawContext) {
|
||||||
|
for inst in &ctx.drawing {
|
||||||
|
match inst {
|
||||||
|
crate::render::DrawInstruction::Text(point, text) => {
|
||||||
|
let (x, y) = (ctx.area.x + point.x, ctx.area.y + point.y);
|
||||||
|
execute!(stdout(), MoveTo(x, y),).unwrap();
|
||||||
|
print!("{text}");
|
||||||
|
stdout().flush().unwrap();
|
||||||
|
}
|
||||||
|
crate::render::DrawInstruction::Child(_point, child) => self.draw_context(child),
|
||||||
|
crate::render::DrawInstruction::View(area, view) => {
|
||||||
|
self.draw_context(&self.render_view(area, view))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::{component, extensions::Extension, widget::Widget, Screen};
|
|
||||||
|
|
||||||
pub struct IdExtension(pub Arc<Screen>);
|
|
||||||
|
|
||||||
component!(Id(pub usize));
|
|
||||||
|
|
||||||
impl Extension for Arc<IdExtension> {}
|
|
||||||
|
|
||||||
impl IdExtension {
|
|
||||||
pub fn new(screen: Arc<Screen>) -> Arc<Self> {
|
|
||||||
Arc::new(IdExtension(screen))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_element(self: &Arc<IdExtension>, id: usize) -> Option<Arc<Widget>> {
|
|
||||||
for elem in self.0.widgets.lock().unwrap().iter() {
|
|
||||||
if let Some(current_id) = elem.get::<Id>() {
|
|
||||||
if current_id.0 == id {
|
|
||||||
return Some(elem.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
use crate::extensions::Extension;
|
|
||||||
|
|
||||||
pub struct InputExtension;
|
|
||||||
|
|
||||||
impl Extension for InputExtension {
|
|
||||||
fn init(&mut self, screen: std::sync::Arc<crate::Screen>) {
|
|
||||||
crossterm::terminal::enable_raw_mode().unwrap();
|
|
||||||
std::thread::spawn(move || loop {
|
|
||||||
if let Ok(e) = crossterm::event::read() {
|
|
||||||
for widget in screen.widgets.lock().unwrap().iter() {
|
|
||||||
widget.event(&e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_close(&mut self, _screen: std::sync::Arc<crate::Screen>) {
|
|
||||||
crossterm::terminal::disable_raw_mode().unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl crate::extensions::Event for crossterm::event::Event {
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
pub mod id;
|
|
||||||
pub mod input_handling;
|
|
||||||
pub mod tick;
|
|
||||||
pub mod velocity;
|
|
||||||
|
|
||||||
pub use id::*;
|
|
||||||
pub use input_handling::*;
|
|
||||||
pub use tick::*;
|
|
||||||
pub use velocity::*;
|
|
||||||
|
|
||||||
use std::{
|
|
||||||
any::{type_name, Any},
|
|
||||||
fmt::Debug,
|
|
||||||
sync::{Arc, Mutex},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
render_scope::RenderScope,
|
|
||||||
widget::{Component, Widget},
|
|
||||||
Screen,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub trait Extension {
|
|
||||||
fn init(&mut self, _screen: Arc<Screen>) {}
|
|
||||||
fn on_close(&mut self, _screen: Arc<Screen>) {}
|
|
||||||
fn render_widget(&mut self, _scope: &mut RenderScope, _widget: &Arc<Widget>) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait Event: Send + Sync {
|
|
||||||
fn as_any(&self) -> &dyn Any;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct Handler<E: Event>(Arc<Mutex<dyn FnMut(&Arc<Widget>, &E) + Send + Sync>>);
|
|
||||||
|
|
||||||
impl<E: Event + 'static> Component for Handler<E> {
|
|
||||||
fn as_any(&self) -> &dyn Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<E: Event + 'static> Handler<E> {
|
|
||||||
pub fn new<F: FnMut(&Arc<Widget>, &E) + Send + Sync + 'static>(f: F) -> Handler<E> {
|
|
||||||
Handler(Arc::new(Mutex::new(f)))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn call(&self, w: &Arc<Widget>, e: &E) {
|
|
||||||
(self.0.lock().unwrap())(w, e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<E: Event> Debug for Handler<E> {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(f, "Handler({})", type_name::<E>())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> dyn Event + 'a {
|
|
||||||
pub fn get<T: Event + 'static>(&self) -> Option<&T> {
|
|
||||||
self.as_any().downcast_ref()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
use std::{fmt::Debug, sync::Arc};
|
|
||||||
|
|
||||||
use crate::extensions::Extension;
|
|
||||||
use crate::{event, Screen};
|
|
||||||
|
|
||||||
pub struct TickExtension(pub u16);
|
|
||||||
|
|
||||||
event!(TickEvent(pub u32));
|
|
||||||
|
|
||||||
impl Extension for TickExtension {
|
|
||||||
fn init(&mut self, screen: Arc<Screen>) {
|
|
||||||
let rate_dur = 1000 / self.0 as u64;
|
|
||||||
std::thread::spawn({
|
|
||||||
move || {
|
|
||||||
let mut tick = 0;
|
|
||||||
loop {
|
|
||||||
for w in screen.widgets.lock().unwrap().iter() {
|
|
||||||
w.event(&TickEvent(tick));
|
|
||||||
}
|
|
||||||
tick += 1;
|
|
||||||
std::thread::sleep(std::time::Duration::from_millis(rate_dur));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
component,
|
|
||||||
extensions::Extension,
|
|
||||||
style::{Position, Transform},
|
|
||||||
widget::Widget,
|
|
||||||
Screen,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct VelocityExtension;
|
|
||||||
|
|
||||||
component!(Velocity(pub i32, pub i32));
|
|
||||||
|
|
||||||
impl VelocityExtension {
|
|
||||||
fn apply_velocity(ticks: u16, velocity: i32, x: &mut u16) {
|
|
||||||
if velocity.abs() != 0 && ticks as i32 % (1000 / velocity.abs()) == 0 {
|
|
||||||
if velocity > 0 {
|
|
||||||
*x += 1;
|
|
||||||
} else if velocity < 0 {
|
|
||||||
*x -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_velocity_xy(ticks: u16, widget: &Arc<Widget>) {
|
|
||||||
if let Some(velocity) = widget.get::<Velocity>() {
|
|
||||||
if let Some(mut t) = widget.get::<Transform>() {
|
|
||||||
match &mut t.x {
|
|
||||||
Position::Const(x) => Self::apply_velocity(ticks, velocity.0, x),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
match &mut t.y {
|
|
||||||
Position::Const(y) => Self::apply_velocity(ticks, velocity.1, y),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
widget.set_component(t);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Extension for VelocityExtension {
|
|
||||||
fn init(&mut self, screen: Arc<Screen>) {
|
|
||||||
std::thread::spawn({
|
|
||||||
move || {
|
|
||||||
let mut tick = 0;
|
|
||||||
loop {
|
|
||||||
for widget in screen.widgets.lock().unwrap().iter() {
|
|
||||||
Self::apply_velocity_xy(tick, widget);
|
|
||||||
}
|
|
||||||
if tick > 1000 {
|
|
||||||
tick = 0;
|
|
||||||
} else {
|
|
||||||
tick += 1;
|
|
||||||
}
|
|
||||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+36
-81
@@ -1,103 +1,58 @@
|
|||||||
//! The frontend binder for OSUI.
|
|
||||||
//!
|
|
||||||
//! This module defines the internal representation of RSX elements — the tree-like structure used
|
|
||||||
//! by the `rsx!` macro in OSUI to declaratively build terminal user interfaces.
|
|
||||||
//!
|
|
||||||
//! RSX elements can be either static widgets or dynamically loaded ones with dependencies.
|
|
||||||
//! This structure enables recursive rendering, parent-child composition, and runtime dependency handling.
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
state::DependencyHandler,
|
component::{Context, Scope},
|
||||||
widget::{StaticWidget, Widget, WidgetLoad},
|
state::HookDependency,
|
||||||
Screen,
|
View,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Represents a single element in the RSX tree.
|
pub enum RsxScope {
|
||||||
pub enum RsxElement {
|
Static(Arc<Scope>),
|
||||||
/// A static widget with children.
|
Dynamic(
|
||||||
Element(StaticWidget, Rsx),
|
Arc<dyn Fn(&Arc<Scope>) + Send + Sync>,
|
||||||
|
Vec<Box<dyn HookDependency>>,
|
||||||
/// A dynamically generated widget (e.g., with state) with associated dependencies and children.
|
|
||||||
DynElement(
|
|
||||||
Box<dyn FnMut() -> WidgetLoad + Send + Sync>,
|
|
||||||
Vec<Box<dyn DependencyHandler>>,
|
|
||||||
Rsx,
|
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A container representing a group of RSX elements.
|
pub struct Rsx(Vec<RsxScope>);
|
||||||
/// This is typically created via the `rsx!` macro and rendered using a `Screen`.
|
|
||||||
pub struct Rsx(pub Vec<RsxElement>);
|
|
||||||
|
|
||||||
impl Rsx {
|
impl Rsx {
|
||||||
/// Draws the RSX tree onto the given screen without a parent widget.
|
pub fn new() -> Self {
|
||||||
///
|
Self(Vec::new())
|
||||||
/// This is the entry point for rendering the UI.
|
|
||||||
pub fn draw(self, screen: &Arc<Screen>) {
|
|
||||||
self.draw_parent(screen, None);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Recursively draws the RSX tree with an optional parent widget.
|
pub fn static_scope(&mut self, scope: Arc<Scope>) {
|
||||||
///
|
self.0.push(RsxScope::Static(scope));
|
||||||
/// Used internally to establish parent-child widget relationships.
|
|
||||||
pub fn draw_parent(self, screen: &Arc<Screen>, parent: Option<Arc<Widget>>) {
|
|
||||||
for rsx_elem in self.0 {
|
|
||||||
match rsx_elem {
|
|
||||||
RsxElement::DynElement(f, dep, child) => {
|
|
||||||
let w = screen.draw_box_dyn(f);
|
|
||||||
|
|
||||||
if let Some(parent) = &parent {
|
|
||||||
parent.get_elem().draw_child(&w);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for d in dep {
|
pub fn dynamic_scope<F: Fn(&Arc<Scope>) + Send + Sync + 'static>(
|
||||||
w.dependency_box(d);
|
|
||||||
}
|
|
||||||
|
|
||||||
child.draw_parent(screen, Some(w.clone()));
|
|
||||||
}
|
|
||||||
|
|
||||||
RsxElement::Element(ws, child) => {
|
|
||||||
let w = Arc::new(Widget::Static(ws));
|
|
||||||
screen.draw_widget(w.clone());
|
|
||||||
|
|
||||||
if let Some(parent) = &parent {
|
|
||||||
parent.get_elem().draw_child(&w);
|
|
||||||
}
|
|
||||||
|
|
||||||
child.draw_parent(screen, Some(w.clone()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a dynamically constructed element to the RSX tree.
|
|
||||||
///
|
|
||||||
/// - `load`: A closure returning a `WidgetLoad` used to generate the widget.
|
|
||||||
/// - `dependencies`: A list of dependency handlers for state or event updates.
|
|
||||||
/// - `children`: Child RSX elements.
|
|
||||||
pub fn create_element<F: FnMut() -> WidgetLoad + Send + Sync + 'static>(
|
|
||||||
&mut self,
|
&mut self,
|
||||||
load: F,
|
drawer: F,
|
||||||
dependencies: Vec<Box<dyn DependencyHandler>>,
|
dependencies: Vec<Box<dyn HookDependency>>,
|
||||||
children: Rsx,
|
|
||||||
) {
|
) {
|
||||||
self.0.push(RsxElement::DynElement(
|
self.0
|
||||||
Box::new(load),
|
.push(RsxScope::Dynamic(Arc::new(drawer), dependencies));
|
||||||
dependencies,
|
|
||||||
children,
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a statically defined element to the RSX tree with its children.
|
pub fn view(&self, context: Arc<Context>) -> View {
|
||||||
pub fn create_element_static(&mut self, element: StaticWidget, children: Rsx) {
|
for scope in &self.0 {
|
||||||
self.0.push(RsxElement::Element(element, children));
|
match scope {
|
||||||
|
RsxScope::Static(scope) => context.scopes.lock().unwrap().push(scope.clone()),
|
||||||
|
RsxScope::Dynamic(drawer, dependencies) => {
|
||||||
|
let drawer = drawer.clone();
|
||||||
|
context.dyn_scope(
|
||||||
|
move |c| drawer(c),
|
||||||
|
&dependencies.iter().map(|d| d.as_ref()).collect::<Vec<_>>(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends the elements from another `Rsx` tree into this one.
|
let context = context.clone();
|
||||||
pub fn expand(&mut self, other: &mut Rsx) {
|
Arc::new({
|
||||||
self.0.append(&mut other.0);
|
move |ctx| {
|
||||||
|
context.draw_children(ctx);
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-226
@@ -1,235 +1,21 @@
|
|||||||
//! **OSUI** – A Rust Terminal User Interface Library
|
use std::sync::Arc;
|
||||||
//!
|
|
||||||
//! OSUI is a library for building interactive and customizable terminal user interfaces in Rust.
|
|
||||||
//! It provides a component system, real-time keyboard input handling, and a `rsx!` macro
|
|
||||||
//! for defining UI elements in a declarative way, however that is optional.
|
|
||||||
//!
|
|
||||||
//! ✅ **Features**
|
|
||||||
//! - 🧱 RSX-like syntax with `rsx!` macro
|
|
||||||
//! - 🖥️ Virtual screen abstraction
|
|
||||||
//! - 🎹 Keyboard input handling
|
|
||||||
//! - 🎯 Component-based design
|
|
||||||
//! - ⚡ Real-time rendering
|
|
||||||
//!
|
|
||||||
//! 🚀 **Quick Example**
|
|
||||||
//! ```rust
|
|
||||||
//! use osui::prelude::*;
|
|
||||||
//!
|
|
||||||
//! fn main() -> std::io::Result<()> {
|
|
||||||
//! let screen = Screen::new();
|
|
||||||
//! rsx! {
|
|
||||||
//! "👋 Hello, World!"
|
|
||||||
//! }.draw(&screen);
|
|
||||||
//! screen.run()
|
|
||||||
//! }
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! ---
|
|
||||||
//! 🧰 For full documentation, visit: [osui.netlify.app/docs](https://osui.netlify.app/docs)
|
|
||||||
//!
|
|
||||||
//! 🧪 Examples and demos: [github.com/osui-rs/osui/demos](https://github.com/osui-rs/osui/tree/master/src/demos)
|
|
||||||
|
|
||||||
use std::sync::{Arc, Mutex};
|
use crate::render::DrawContext;
|
||||||
|
|
||||||
use crate::{
|
pub mod component;
|
||||||
extensions::{Extension, Handler},
|
pub mod engine;
|
||||||
render_scope::RenderScope,
|
|
||||||
widget::{BoxedElement, DynWidget, Element, StaticWidget, Widget, WidgetLoad},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub mod elements;
|
|
||||||
pub mod extensions;
|
|
||||||
pub mod frontend;
|
pub mod frontend;
|
||||||
pub mod macros;
|
pub mod macros;
|
||||||
pub mod render_scope;
|
pub mod render;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
pub mod style;
|
|
||||||
pub mod utils;
|
|
||||||
pub mod widget;
|
|
||||||
|
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
pub use crate::{
|
pub use crate::component::*;
|
||||||
elements::*, extensions::*, frontend::*, render_scope::*, state::*, style::*, utils::*,
|
pub use crate::engine::*;
|
||||||
widget::*, *,
|
pub use crate::render::*;
|
||||||
};
|
pub use crate::state::*;
|
||||||
|
pub use crate::View;
|
||||||
pub use crate::style::{
|
|
||||||
Dimension::{Content, Full},
|
|
||||||
Position::{Center, End},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The main screen abstraction for rendering and managing widgets and extensions.
|
pub type View = Arc<dyn Fn(&mut DrawContext) + Send + Sync>;
|
||||||
///
|
pub type ViewWrapper = Arc<dyn Fn(&mut DrawContext, View) + Send + Sync>;
|
||||||
/// `Screen` holds the root widget list and registered extensions. It provides methods
|
|
||||||
/// for drawing elements, adding extensions, and running the main rendering loop.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```rust
|
|
||||||
/// let screen = Screen::new();
|
|
||||||
/// rsx! { "Hello" }.draw(&screen);
|
|
||||||
/// screen.run()?;
|
|
||||||
/// ```
|
|
||||||
pub struct Screen {
|
|
||||||
/// The list of widgets currently managed by the screen.
|
|
||||||
pub widgets: Mutex<Vec<Arc<Widget>>>,
|
|
||||||
/// Registered extensions for the screen.
|
|
||||||
extensions: Mutex<Vec<Arc<Mutex<Box<dyn Extension + Send + Sync>>>>>,
|
|
||||||
/// If it's still running
|
|
||||||
running: Mutex<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
event!(RenderWrapperEvent(*mut RenderScope));
|
|
||||||
component!(NoRender);
|
|
||||||
component!(NoRenderRoot);
|
|
||||||
|
|
||||||
impl RenderWrapperEvent {
|
|
||||||
/// Returns a mutable reference to the underlying `RenderScope`.
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
/// The caller must ensure the pointer is valid for the lifetime of the event.
|
|
||||||
pub fn get_scope(&self) -> &mut RenderScope {
|
|
||||||
unsafe { &mut *self.0 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for RenderWrapperEvent {}
|
|
||||||
unsafe impl Sync for RenderWrapperEvent {}
|
|
||||||
|
|
||||||
impl Screen {
|
|
||||||
/// Creates a new screen instance wrapped in an `Arc`.
|
|
||||||
pub fn new() -> Arc<Self> {
|
|
||||||
Arc::new(Self {
|
|
||||||
widgets: Mutex::new(Vec::new()),
|
|
||||||
extensions: Mutex::new(Vec::new()),
|
|
||||||
running: Mutex::new(true),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Draws a static element and returns its widget handle.
|
|
||||||
pub fn draw<E: Element + 'static + Send + Sync>(self: &Arc<Self>, element: E) -> Arc<Widget> {
|
|
||||||
let w = Arc::new(Widget::Static(StaticWidget::new(Box::new(element))));
|
|
||||||
self.widgets.lock().unwrap().push(w.clone());
|
|
||||||
w
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Draws a boxed element and returns its widget handle.
|
|
||||||
pub fn draw_box(self: &Arc<Self>, element: BoxedElement) -> Arc<Widget> {
|
|
||||||
let w = Arc::new(Widget::Static(StaticWidget::new(element)));
|
|
||||||
self.widgets.lock().unwrap().push(w.clone());
|
|
||||||
w
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds an existing widget to the screen.
|
|
||||||
pub fn draw_widget(self: &Arc<Self>, widget: Arc<Widget>) {
|
|
||||||
self.widgets.lock().unwrap().push(widget);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Draws a dynamic element using a closure and returns its widget handle.
|
|
||||||
pub fn draw_dyn<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
element: F,
|
|
||||||
) -> Arc<Widget> {
|
|
||||||
let w = Arc::new(Widget::Dynamic(DynWidget::new(element)));
|
|
||||||
self.widgets.lock().unwrap().push(w.clone());
|
|
||||||
w
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Draws a dynamic element from a boxed closure and returns its widget handle.
|
|
||||||
pub fn draw_box_dyn(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
element: Box<dyn FnMut() -> WidgetLoad + Send + Sync>,
|
|
||||||
) -> Arc<Widget> {
|
|
||||||
let w = Arc::new(Widget::Dynamic(DynWidget::new(element)));
|
|
||||||
self.widgets.lock().unwrap().push(w.clone());
|
|
||||||
w
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Registers an extension with the screen.
|
|
||||||
pub fn extension<E: Extension + Send + Sync + 'static>(self: &Arc<Self>, ext: E) {
|
|
||||||
self.extensions
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.push(Arc::new(Mutex::new(Box::new(ext))));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs the main rendering loop, calling extensions and rendering widgets.
|
|
||||||
///
|
|
||||||
/// This method blocks and repeatedly renders the screen at a fixed interval.
|
|
||||||
pub fn run(self: &Arc<Self>) -> std::io::Result<()> {
|
|
||||||
for ext in self.extensions.lock().unwrap().iter() {
|
|
||||||
ext.lock().unwrap().init(self.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
utils::hide_cursor()?;
|
|
||||||
|
|
||||||
while *self.running.lock().unwrap() {
|
|
||||||
self.render()?;
|
|
||||||
std::thread::sleep(std::time::Duration::from_millis(28));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders all widgets and applies extensions.
|
|
||||||
///
|
|
||||||
/// This method is called internally by `run`.
|
|
||||||
pub fn render(self: &Arc<Self>) -> std::io::Result<()> {
|
|
||||||
let mut scope = RenderScope::new();
|
|
||||||
let (w, h) = crossterm::terminal::size().unwrap();
|
|
||||||
scope.set_parent_size(w, h);
|
|
||||||
|
|
||||||
utils::clear()?;
|
|
||||||
for elem in self.widgets.lock().unwrap().iter() {
|
|
||||||
if elem.get::<NoRender>().is_some() || elem.get::<NoRenderRoot>().is_some() {
|
|
||||||
for ext in self.extensions.lock().unwrap().iter() {
|
|
||||||
ext.lock().unwrap().render_widget(&mut scope, elem);
|
|
||||||
}
|
|
||||||
elem.auto_refresh();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(wrapper) = elem.get::<Handler<RenderWrapperEvent>>() {
|
|
||||||
wrapper.call(elem, &RenderWrapperEvent(&mut scope));
|
|
||||||
} else {
|
|
||||||
scope.clear();
|
|
||||||
|
|
||||||
if let Some(style) = elem.get() {
|
|
||||||
scope.set_style(style);
|
|
||||||
}
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
|
|
||||||
for ext in self.extensions.lock().unwrap().iter() {
|
|
||||||
ext.lock().unwrap().render_widget(&mut scope, elem);
|
|
||||||
}
|
|
||||||
|
|
||||||
elem.get_elem().render(&mut scope);
|
|
||||||
|
|
||||||
if let Some(t) = elem.get() {
|
|
||||||
scope.set_transform(&t);
|
|
||||||
}
|
|
||||||
scope.draw();
|
|
||||||
|
|
||||||
elem.get_elem().after_render(&mut scope);
|
|
||||||
}
|
|
||||||
|
|
||||||
elem.auto_refresh();
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Closes the loop and calls `on_close` in the extensions
|
|
||||||
pub fn close(self: &Arc<Self>) {
|
|
||||||
*self.running.lock().unwrap() = false;
|
|
||||||
|
|
||||||
utils::show_cursor().unwrap();
|
|
||||||
|
|
||||||
utils::clear().unwrap();
|
|
||||||
|
|
||||||
for ext in self.extensions.lock().unwrap().iter() {
|
|
||||||
ext.lock().unwrap().on_close(self.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+142
-278
@@ -1,301 +1,165 @@
|
|||||||
/// Declares a struct that implements the `Event` trait.
|
|
||||||
///
|
|
||||||
/// This macro simplifies the creation of event types used within OSUI's reactive system.
|
|
||||||
///
|
|
||||||
/// # Variants
|
|
||||||
///
|
|
||||||
/// - `event!(Name)`
|
|
||||||
/// Defines a unit struct named `Name`.
|
|
||||||
///
|
|
||||||
/// - `event!(Name { ... })`
|
|
||||||
/// Defines a named struct with fields.
|
|
||||||
///
|
|
||||||
/// - `event!(Name (...))`
|
|
||||||
/// Defines a tuple struct.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```rust
|
|
||||||
/// event!(Clicked);
|
|
||||||
/// event!(Resized { width: u32, height: u32 });
|
|
||||||
/// event!(Moved(u32, u32));
|
|
||||||
/// ```
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! event {
|
|
||||||
($name:ident) => {
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct $name;
|
|
||||||
|
|
||||||
impl $crate::extensions::Event for $name {
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
($name:ident {$($inner:tt)*}) => {
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct $name {
|
|
||||||
$($inner)*
|
|
||||||
}
|
|
||||||
|
|
||||||
impl $crate::extensions::Event for $name {
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
($name:ident ($($inner:tt)*)) => {
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct $name ($($inner)*);
|
|
||||||
|
|
||||||
impl $crate::extensions::Event for $name {
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Declares a struct that implements the `Component` trait.
|
|
||||||
///
|
|
||||||
/// Components allow widgets to extend their behavior or contain additional data.
|
|
||||||
/// This macro helps avoid boilerplate when defining new components.
|
|
||||||
///
|
|
||||||
/// # Variants
|
|
||||||
///
|
|
||||||
/// - `component!(Name)`
|
|
||||||
/// Defines a unit struct.
|
|
||||||
///
|
|
||||||
/// - `component!(Name { ... })`
|
|
||||||
/// Defines a named struct with fields.
|
|
||||||
///
|
|
||||||
/// - `component!(Name (...))`
|
|
||||||
/// Defines a tuple struct.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```rust
|
|
||||||
/// component!(Focusable);
|
|
||||||
/// component!(Tooltip { text: String });
|
|
||||||
/// component!(Size(u32, u32));
|
|
||||||
/// ```
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! component {
|
|
||||||
($name:ident) => {
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct $name;
|
|
||||||
|
|
||||||
impl $crate::widget::Component for $name {
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
($name:ident {$($inner:tt)*}) => {
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct $name {
|
|
||||||
$($inner)*
|
|
||||||
}
|
|
||||||
|
|
||||||
impl $crate::widget::Component for $name {
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
($name:ident ($($inner:tt)*)) => {
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct $name ($($inner)*);
|
|
||||||
|
|
||||||
impl $crate::widget::Component for $name {
|
|
||||||
fn as_any(&self) -> &dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates an event handler closure that calls a method on `self`.
|
|
||||||
///
|
|
||||||
/// Useful when you need to register `'static` event handlers that interact with the current instance.
|
|
||||||
///
|
|
||||||
/// # Arguments
|
|
||||||
/// - `$self_ty`: The type of `self`.
|
|
||||||
/// - `$self`: The instance variable (usually `self`) being used.
|
|
||||||
/// - `$events`: The event source object with an `.on` method.
|
|
||||||
/// - `$method`: The method to call when an event is received.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```rust
|
|
||||||
/// event_handler!(Self, self, events, on_event);
|
|
||||||
/// ```
|
|
||||||
/// Expands roughly to:
|
|
||||||
/// ```rust
|
|
||||||
/// let self_ref = self as *mut Self;
|
|
||||||
/// events.on(move |es, e| unsafe { (*self_ref).on_event(es, e) });
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
/// This macro uses `unsafe` code to cast `self` to a raw pointer and dereference it.
|
|
||||||
/// Make sure the reference is valid for the closure’s lifetime.
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! event_handler {
|
|
||||||
($self_ty:ty, $self:ident, $events:ident, $method:ident) => {{
|
|
||||||
let self_ref = $self as *mut $self_ty;
|
|
||||||
$events.on(move |es, e| unsafe { (*self_ref).$method(es, e) });
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a `Transform` with property overrides.
|
|
||||||
///
|
|
||||||
/// Each key-value pair sets a field on a `Transform` struct.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```rust
|
|
||||||
/// let t = transform!(
|
|
||||||
/// x: 10,
|
|
||||||
/// y: 20,
|
|
||||||
/// scale: 1.5,
|
|
||||||
/// );
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// This expands to:
|
|
||||||
/// ```rust
|
|
||||||
/// let mut t = Transform::new();
|
|
||||||
/// t.x = 10.into();
|
|
||||||
/// t.y = 20.into();
|
|
||||||
/// t.scale = 1.5.into();
|
|
||||||
/// ```
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! transform {
|
|
||||||
($($f:ident: $v:expr),* $(,)?) => {{
|
|
||||||
let mut t = Transform::new();
|
|
||||||
$(t.$f = $v.into();)*
|
|
||||||
t
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Constructs an `Rsx` tree using declarative syntax.
|
|
||||||
///
|
|
||||||
/// This macro is similar to JSX in UI frameworks, allowing you to nest widgets and assign components or dependencies.
|
|
||||||
/// It expands into a tree of `RsxElement` objects.
|
|
||||||
///
|
|
||||||
/// Internally calls the recursive `rsx_inner!` macro.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```rust
|
|
||||||
/// rsx! {
|
|
||||||
/// "Hello"
|
|
||||||
/// static Label { } ("Text")
|
|
||||||
/// %state Label { }
|
|
||||||
/// @Velocity(20, 0); Transform::new(); "Moving Text"
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! rsx {
|
macro_rules! rsx {
|
||||||
($($inner:tt)*) => {{
|
() => {
|
||||||
let mut r = $crate::frontend::Rsx(Vec::new());
|
$crate::frontend::Rsx::new()
|
||||||
|
};
|
||||||
$crate::rsx_inner! { r, $($inner)* };
|
|
||||||
|
|
||||||
|
($($rsx:tt)+) => {{
|
||||||
|
let mut r = $crate::frontend::Rsx::new();
|
||||||
|
{
|
||||||
|
$crate::rsx_scope!(r, $($rsx)+);
|
||||||
|
}
|
||||||
r
|
r
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Internal macro used by `rsx!` to recursively build `Rsx` trees.
|
|
||||||
///
|
|
||||||
/// This macro handles various syntactic forms used in the declarative layout system:
|
|
||||||
///
|
|
||||||
/// - Static text or components
|
|
||||||
/// - Dynamic widgets with dependencies (`%dep`)
|
|
||||||
/// - Component annotations (`@comp`)
|
|
||||||
/// - Argument passing to constructors
|
|
||||||
/// - Nesting and expansion from other `Rsx` blocks
|
|
||||||
///
|
|
||||||
/// **This macro is not intended for direct use**; use `rsx!` instead.
|
|
||||||
///
|
|
||||||
/// # Example expansion
|
|
||||||
/// ```rust
|
|
||||||
/// rsx! {
|
|
||||||
/// static Label { } ("Title")
|
|
||||||
/// %state Label { inner }
|
|
||||||
/// "Text"
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Would produce a nested `Rsx` tree of static and dynamic widgets.
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! rsx_inner {
|
macro_rules! rsx_scope {
|
||||||
// static
|
($rsx:expr, for $(%$($dep:ident $(as $dp:pat,)?),+)? ($p:pat in $v:expr) {$($inner:tt)*} $($rest:tt)*) => {
|
||||||
($r:expr, $(@$comp:expr;)* static $s:literal $($rest:tt)*) => {
|
{
|
||||||
let w = $crate::widget::StaticWidget::new(Box::new(format!($s)));
|
$($($crate::rsx_dep!($dep);)+)?
|
||||||
$(w.component($comp);)*
|
|
||||||
$r.create_element_static(w, $crate::frontend::Rsx(Vec::new()));
|
$rsx.dynamic_scope({
|
||||||
$crate::rsx_inner! { $r, $($rest)* };
|
$($($crate::rsx_dep!($dep $(as $dp)?);)+)?
|
||||||
|
move |scope| {
|
||||||
|
scope.children.lock().unwrap().clear();
|
||||||
|
for $p in $v {
|
||||||
|
$crate::rsx_child!(scope, $($inner)*);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, vec![$($(Box::new($dep)),+)?]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_scope!($rsx, $($rest)*);
|
||||||
};
|
};
|
||||||
|
|
||||||
($r:expr, $(@$comp:expr;)* $(%$dep:ident)* $s:literal $($rest:tt)*) => {
|
($rsx:expr, if $(%$($dep:ident $(as $dp:pat,)?),+)? ($st:expr) {$($inner:tt)*} $($rest:tt)*) => {
|
||||||
$r.create_element({ $(let $dep = $dep.clone();)* move || {
|
{
|
||||||
$crate::widget::WidgetLoad::new(format!($s)) $(.component($comp))*
|
$($($crate::rsx_dep!($dep);)+)?
|
||||||
} }, vec![$(Box::new($dep.clone())),*], $crate::frontend::Rsx(Vec::new()));
|
|
||||||
$crate::rsx_inner! { $r, $($rest)* };
|
$rsx.dynamic_scope({
|
||||||
|
$($($crate::rsx_dep!($dep $(as $dp)?);)+)?
|
||||||
|
move |scope| {
|
||||||
|
if $st {
|
||||||
|
if scope.children.lock().unwrap().len() == 0 {
|
||||||
|
$crate::rsx_child!(scope, $($inner)*);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scope.children.lock().unwrap().clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, vec![$($(Box::new($dep)),+)?]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_scope!($rsx, $($rest)*);
|
||||||
};
|
};
|
||||||
|
|
||||||
// static
|
($rsx:expr, $(%$($dep:ident $(as $dp:pat,)?),+)? $text:literal @$d:expr; $($rest:tt)*) => {
|
||||||
($r:expr, $(@$comp:expr;)* static $name:path, $($f:ident $(: $v:expr)?),+, { $($inner:tt)* } $($rest:tt)*) => {
|
{
|
||||||
let w = $crate::widget::StaticWidget::new(Box::new({
|
let scope = $crate::component::Scope::new();
|
||||||
let mut elem = <$name>::new();
|
|
||||||
$(elem.$f = $($v)?;)+
|
$($($crate::rsx_dep!($dep $(as $dp)?);)+)?
|
||||||
elem
|
|
||||||
}));
|
$crate::rsx_child!(scope, $text @$d;);
|
||||||
$(w.component($comp);)*
|
|
||||||
$r.create_element_static(w, $crate::rsx!{ $($inner)* });
|
$rsx.static_scope(scope);
|
||||||
$crate::rsx_inner! { $r, $($rest)* };
|
}
|
||||||
|
|
||||||
|
$crate::rsx_scope!($rsx, $($rest)*);
|
||||||
};
|
};
|
||||||
|
|
||||||
($r:expr, $(@$comp:expr;)* static $name:path { $($inner:tt)* } $($rest:tt)*) => {
|
($rsx:expr, $(%$($dep:ident $(as $dp:pat,)?),+)? $text:literal $($rest:tt)*) => {
|
||||||
let w = $crate::widget::StaticWidget::new(Box::new(<$name>::new()));
|
{
|
||||||
$(w.component($comp);)*
|
let scope = $crate::component::Scope::new();
|
||||||
$r.create_element_static(w, $crate::rsx!{ $($inner)* });
|
|
||||||
$crate::rsx_inner! { $r, $($rest)* };
|
$($($crate::rsx_dep!($dep $(as $dp)?);)+)?
|
||||||
|
|
||||||
|
$crate::rsx_child!(scope, $text);
|
||||||
|
|
||||||
|
$rsx.static_scope(scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_scope!($rsx, $($rest)*);
|
||||||
};
|
};
|
||||||
|
|
||||||
($r:expr, $(@$comp:expr;)* $(%$dep:ident)* $name:path, $($f:ident $(: $v:expr)?),+, { $($inner:tt)* } $($rest:tt)*) => {
|
($rsx:expr, $component:ident ($ctx:ident, $view:ident) $body:block $($rest:tt)*) => {
|
||||||
$r.create_element({ $(let $dep = $dep.clone();)* move || {
|
{
|
||||||
$crate::widget::WidgetLoad::new({
|
let scope = $crate::component::Scope::new();
|
||||||
let mut elem = <$name>::new();
|
|
||||||
$(elem.$f = $($v)?;)+
|
$crate::rsx_child!(scope, $component ($ctx, $view) $body);
|
||||||
elem
|
|
||||||
}) $(.component($comp))*
|
$rsx.static_scope(scope);
|
||||||
} }, vec![$(Box::new($dep.clone())),*], $crate::rsx!{ $($inner)* });
|
}
|
||||||
$crate::rsx_inner! { $r, $($rest)* };
|
|
||||||
|
$crate::rsx_scope!($rsx, $($rest)*);
|
||||||
};
|
};
|
||||||
|
|
||||||
($r:expr, $(@$comp:expr;)* $(%$dep:ident)* $name:path { $($inner:tt)* } $($rest:tt)*) => {
|
($rsx:expr, $component:ident $($rest:tt)*) => {
|
||||||
$r.create_element({ $(let $dep = $dep.clone();)* move || {
|
{
|
||||||
$crate::widget::WidgetLoad::new(<$name>::new()) $(.component($comp))*
|
let scope = $crate::component::Scope::new();
|
||||||
} }, vec![$(Box::new($dep.clone())),*], $crate::rsx!{ $($inner)* });
|
|
||||||
$crate::rsx_inner! { $r, $($rest)* };
|
$crate::rsx_child!(scope, $component);
|
||||||
|
|
||||||
|
$rsx.static_scope(scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_scope!($rsx, $($rest)*);
|
||||||
};
|
};
|
||||||
|
|
||||||
($r:expr, $expand:ident => ($($inner:tt)*) $($rest:tt)*) => {
|
($rsx:expr, !mount $mount:ident $($rest:tt)*) => {
|
||||||
$r.expand(&mut $expand($($inner)*));
|
{
|
||||||
$crate::rsx_inner! { $r, $($rest)* };
|
$mount.mount();
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_scope!($rsx, $($rest)*);
|
||||||
};
|
};
|
||||||
|
|
||||||
($r:expr,) => {};
|
($rsx:expr,) => {};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! rsx_child {
|
||||||
|
($scope:expr, $text:literal @$d:expr; $($rest:tt)*) => {
|
||||||
|
{
|
||||||
|
$scope.view(Arc::new(move |ctx| ctx.draw_text($d, &format!($text))));
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_child!($scope, $($rest)*);
|
||||||
|
};
|
||||||
|
|
||||||
|
($scope:expr, $text:literal $($rest:tt)*) => {
|
||||||
|
{
|
||||||
|
$scope.view(Arc::new(move |ctx| ctx.draw_text(Point { x: 0, y: 0 }, &format!($text))));
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_child!($scope, $($rest)*);
|
||||||
|
};
|
||||||
|
|
||||||
|
($scope:expr, $component:ident ($ctx:ident, $view:ident) $body:block $($rest:tt)*) => {
|
||||||
|
{
|
||||||
|
$scope.child($component, Some(Arc::new(|$ctx, $view| $body)));
|
||||||
|
}
|
||||||
|
|
||||||
|
$crate::rsx_child!($scope, $($rest)*);
|
||||||
|
};
|
||||||
|
|
||||||
|
($scope:expr, $component:ident $($rest:tt)*) => {
|
||||||
|
{
|
||||||
|
$scope.child($component, None);
|
||||||
|
}
|
||||||
|
$crate::rsx_child!($scope, $($rest)*);
|
||||||
|
};
|
||||||
|
|
||||||
|
($rsx:expr,) => {};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! rsx_dep {
|
||||||
|
($dep:ident as $dp:pat) => {
|
||||||
|
let $dp = $dep.clone();
|
||||||
|
};
|
||||||
|
|
||||||
|
($dep:ident) => {
|
||||||
|
let $dep = $dep.clone();
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
-11
@@ -1,11 +0,0 @@
|
|||||||
mod demos;
|
|
||||||
use osui::prelude::*;
|
|
||||||
|
|
||||||
fn main() -> std::io::Result<()> {
|
|
||||||
let screen = Screen::new();
|
|
||||||
screen.extension(InputExtension);
|
|
||||||
|
|
||||||
demos::app(screen.clone()).draw(&screen);
|
|
||||||
|
|
||||||
screen.run()
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
use crate::View;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum DrawInstruction {
|
||||||
|
Text(Point, String),
|
||||||
|
View(Area, View),
|
||||||
|
Child(Point, DrawContext),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Size {
|
||||||
|
pub width: u16,
|
||||||
|
pub height: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Point {
|
||||||
|
pub x: u16,
|
||||||
|
pub y: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Area {
|
||||||
|
pub x: u16,
|
||||||
|
pub y: u16,
|
||||||
|
pub width: u16,
|
||||||
|
pub height: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DrawContext {
|
||||||
|
pub area: Area,
|
||||||
|
pub allocated: Area,
|
||||||
|
pub drawing: Vec<DrawInstruction>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DrawContext {
|
||||||
|
pub fn new(area: Area) -> Self {
|
||||||
|
Self {
|
||||||
|
area,
|
||||||
|
allocated: Area {
|
||||||
|
x: u16::MAX,
|
||||||
|
y: u16::MAX,
|
||||||
|
width: 0,
|
||||||
|
height: 0,
|
||||||
|
},
|
||||||
|
drawing: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn allocate(&mut self, x: u16, y: u16, width: u16, height: u16) -> Area {
|
||||||
|
self.allocated.x = self.allocated.x.min(x);
|
||||||
|
self.allocated.y = self.allocated.y.min(y);
|
||||||
|
self.allocated.width = self.allocated.width.max(width);
|
||||||
|
self.allocated.height = self.allocated.height.max(height);
|
||||||
|
|
||||||
|
Area {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw(&mut self, inst: DrawInstruction) {
|
||||||
|
self.drawing.push(inst);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_text(&mut self, point: Point, text: &str) {
|
||||||
|
self.drawing
|
||||||
|
.push(DrawInstruction::Text(point, text.to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_view(&mut self, area: Area, view: View) {
|
||||||
|
self.drawing.push(DrawInstruction::View(area, view));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,300 +0,0 @@
|
|||||||
//! Rendering logic and layout scope management for OSUI.
|
|
||||||
//!
|
|
||||||
//! `RenderScope` is responsible for handling transformations, parent-child dimensions,
|
|
||||||
//! stacking draw operations, and rendering styled output to the terminal.
|
|
||||||
//!
|
|
||||||
//! This module allows widgets to accumulate rendering commands (text, shapes, colors),
|
|
||||||
//! and then flush them to the screen with correct styling and positioning.
|
|
||||||
//!
|
|
||||||
//! Used internally by OSUI's layout and rendering system.
|
|
||||||
|
|
||||||
use std::fmt::Debug;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
style::{RawTransform, Style, Transform},
|
|
||||||
utils::{self, hex_ansi_bg},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Represents a single render instruction.
|
|
||||||
#[derive(Clone)]
|
|
||||||
enum RenderMethod {
|
|
||||||
/// Plain text rendering at current transform.
|
|
||||||
Text(u16, u16, String),
|
|
||||||
/// Plain text rendering at current transform with the bg and fg swapped.
|
|
||||||
TextInverted(u16, u16, String),
|
|
||||||
/// Text rendered with a specific 24-bit color.
|
|
||||||
TextColored(u16, u16, String, u32),
|
|
||||||
/// A filled rectangle of a given size and background color.
|
|
||||||
Rectangle(u16, u16, u16, u16, u32),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stores renderable state and transformation data for a single UI widget.
|
|
||||||
///
|
|
||||||
/// `RenderScope` tracks dimensions, styles, and draw commands such as text or
|
|
||||||
/// background rectangles. It accumulates instructions that are later executed in the `draw` method.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct RenderScope {
|
|
||||||
transform: RawTransform,
|
|
||||||
render_stack: Vec<RenderMethod>,
|
|
||||||
parent_width: u16,
|
|
||||||
parent_height: u16,
|
|
||||||
style: Style,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RenderScope {
|
|
||||||
/// Creates a new, empty `RenderScope`.
|
|
||||||
pub fn new() -> RenderScope {
|
|
||||||
RenderScope {
|
|
||||||
transform: RawTransform::new(),
|
|
||||||
render_stack: Vec::new(),
|
|
||||||
parent_width: 0,
|
|
||||||
parent_height: 0,
|
|
||||||
style: Style::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Directly sets the raw transform (position and size) for this scope.
|
|
||||||
pub fn set_transform_raw(&mut self, transform: RawTransform) {
|
|
||||||
self.transform = transform;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Applies a `Transform` to this scope, factoring in parent dimensions.
|
|
||||||
pub fn set_transform(&mut self, transform: &Transform) {
|
|
||||||
transform.use_dimensions(self.parent_width, self.parent_height, &mut self.transform);
|
|
||||||
transform.use_position(self.parent_width, self.parent_height, &mut self.transform);
|
|
||||||
self.transform.px = transform.px;
|
|
||||||
self.transform.py = transform.py;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a text draw instruction.
|
|
||||||
pub fn draw_text(&mut self, x: u16, y: u16, text: &str) {
|
|
||||||
self.render_stack
|
|
||||||
.push(RenderMethod::Text(x, y, text.to_string()));
|
|
||||||
let (w, h) = utils::str_size(text);
|
|
||||||
self.transform.width = self.transform.width.max(w);
|
|
||||||
self.transform.height = self.transform.height.max(h);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a text draw instruction.
|
|
||||||
pub fn draw_text_inverted(&mut self, x: u16, y: u16, text: &str) {
|
|
||||||
self.render_stack
|
|
||||||
.push(RenderMethod::TextInverted(x, y, text.to_string()));
|
|
||||||
let (w, h) = utils::str_size(text);
|
|
||||||
self.transform.width = self.transform.width.max(w);
|
|
||||||
self.transform.height = self.transform.height.max(h);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a colored text draw instruction.
|
|
||||||
pub fn draw_text_colored(&mut self, x: u16, y: u16, text: &str, color: u32) {
|
|
||||||
self.render_stack
|
|
||||||
.push(RenderMethod::TextColored(x, y, text.to_string(), color));
|
|
||||||
let (w, h) = utils::str_size(text);
|
|
||||||
self.transform.width = self.transform.width.max(w);
|
|
||||||
self.transform.height = self.transform.height.max(h);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a background rectangle draw instruction.
|
|
||||||
pub fn draw_rect(&mut self, x: u16, y: u16, width: u16, height: u16, color: u32) {
|
|
||||||
self.render_stack
|
|
||||||
.push(RenderMethod::Rectangle(x, y, width, height, color));
|
|
||||||
self.transform.width = self.transform.width.max(width);
|
|
||||||
self.transform.height = self.transform.height.max(height);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Manually ensures a minimum area is allocated.
|
|
||||||
pub fn use_area(&mut self, width: u16, height: u16) {
|
|
||||||
self.transform.width = self.transform.width.max(width);
|
|
||||||
self.transform.height = self.transform.height.max(height);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders the current stack to the terminal.
|
|
||||||
///
|
|
||||||
/// This will draw background styles (e.g. solid fill or outline) first,
|
|
||||||
/// followed by each draw instruction in the stack.
|
|
||||||
pub fn draw(&self) {
|
|
||||||
let width = self.transform.width;
|
|
||||||
let height = self.transform.height;
|
|
||||||
|
|
||||||
match self.style.background {
|
|
||||||
crate::style::Background::NoBackground => {}
|
|
||||||
crate::style::Background::Outline(c) => {
|
|
||||||
let width = width + self.transform.px * 2;
|
|
||||||
let height = height + self.transform.py * 2;
|
|
||||||
if width > 1 && height > 1 {
|
|
||||||
let d = "─".repeat(width as usize - 2);
|
|
||||||
utils::print_liner(
|
|
||||||
self.transform.x,
|
|
||||||
self.transform.y,
|
|
||||||
&utils::hex_ansi(c),
|
|
||||||
&format!(
|
|
||||||
"┌{d}┐{}\n└{d}┘",
|
|
||||||
format!("\n│{}│", " ".repeat(width as usize - 2))
|
|
||||||
.repeat(height as usize - 2),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
crate::style::Background::RoundedOutline(c) => {
|
|
||||||
let width = width + self.transform.px * 2;
|
|
||||||
let height = height + self.transform.py * 2;
|
|
||||||
if width > 1 && height > 1 {
|
|
||||||
let d = "─".repeat(width as usize - 2);
|
|
||||||
utils::print_liner(
|
|
||||||
self.transform.x,
|
|
||||||
self.transform.y,
|
|
||||||
&utils::hex_ansi(c),
|
|
||||||
&format!(
|
|
||||||
"╭{d}╮{}\n╰{d}╯",
|
|
||||||
format!("\n│{}│", " ".repeat(width as usize - 2))
|
|
||||||
.repeat(height as usize - 2),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
crate::style::Background::Solid(c) => utils::print_liner(
|
|
||||||
self.transform.x,
|
|
||||||
self.transform.y,
|
|
||||||
&hex_ansi_bg(c),
|
|
||||||
&std::iter::repeat(" ".repeat(width as usize))
|
|
||||||
.take(height as usize)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
for m in &self.render_stack {
|
|
||||||
match m {
|
|
||||||
RenderMethod::Text(x, y, t) => {
|
|
||||||
if let Some(c) = self.style.foreground {
|
|
||||||
utils::print_liner(
|
|
||||||
self.transform.x + self.transform.px + x,
|
|
||||||
self.transform.y + self.transform.py + y,
|
|
||||||
&utils::hex_ansi(c),
|
|
||||||
t,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
utils::print(
|
|
||||||
self.transform.x + self.transform.px,
|
|
||||||
self.transform.y + self.transform.py,
|
|
||||||
t,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
RenderMethod::TextInverted(x, y, t) => {
|
|
||||||
if let Some(c) = self.style.foreground {
|
|
||||||
utils::print_liner(
|
|
||||||
self.transform.x + self.transform.px + x,
|
|
||||||
self.transform.y + self.transform.py + y,
|
|
||||||
&utils::hex_ansi_bg(c),
|
|
||||||
t,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
utils::print(
|
|
||||||
self.transform.x + self.transform.px,
|
|
||||||
self.transform.y + self.transform.py,
|
|
||||||
t,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
RenderMethod::TextColored(x, y, t, c) => utils::print_liner(
|
|
||||||
self.transform.x + self.transform.px + x,
|
|
||||||
self.transform.y + self.transform.py + y,
|
|
||||||
&utils::hex_ansi(*c),
|
|
||||||
t,
|
|
||||||
),
|
|
||||||
RenderMethod::Rectangle(x, y, width, height, color) => {
|
|
||||||
utils::print_liner(
|
|
||||||
self.transform.x + self.transform.px + x,
|
|
||||||
self.transform.y + self.transform.py + y,
|
|
||||||
&hex_ansi_bg(*color),
|
|
||||||
&std::iter::repeat(" ".repeat(*width as usize))
|
|
||||||
.take(*height as usize)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Clears all render instructions and resets the internal state.
|
|
||||||
pub fn clear(&mut self) {
|
|
||||||
self.render_stack.clear();
|
|
||||||
self.transform = RawTransform::new();
|
|
||||||
self.style = Style::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the currently used width and height.
|
|
||||||
pub fn get_size(&self) -> (u16, u16) {
|
|
||||||
(self.transform.width, self.transform.height)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns current size, or defaults if size is zero.
|
|
||||||
pub fn get_size_or(&self, width: u16, height: u16) -> (u16, u16) {
|
|
||||||
(
|
|
||||||
if self.transform.width == 0 {
|
|
||||||
width
|
|
||||||
} else {
|
|
||||||
self.transform.width
|
|
||||||
},
|
|
||||||
if self.transform.height == 0 {
|
|
||||||
height
|
|
||||||
} else {
|
|
||||||
self.transform.height
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns size, falling back to parent size if unset.
|
|
||||||
pub fn get_size_or_parent(&self) -> (u16, u16) {
|
|
||||||
(
|
|
||||||
if self.transform.width == 0 {
|
|
||||||
self.parent_width
|
|
||||||
} else {
|
|
||||||
self.transform.width
|
|
||||||
},
|
|
||||||
if self.transform.height == 0 {
|
|
||||||
self.parent_height
|
|
||||||
} else {
|
|
||||||
self.transform.height
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the dimensions of the parent container.
|
|
||||||
pub fn get_parent_size(&self) -> (u16, u16) {
|
|
||||||
(self.parent_width, self.parent_height)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the dimensions of the parent container.
|
|
||||||
pub fn set_parent_size(&mut self, width: u16, height: u16) {
|
|
||||||
self.parent_width = width;
|
|
||||||
self.parent_height = height;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a mutable reference to the internal raw transform.
|
|
||||||
pub fn get_transform_mut(&mut self) -> &mut RawTransform {
|
|
||||||
&mut self.transform
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a reference to the internal raw transform.
|
|
||||||
pub fn get_transform(&self) -> &RawTransform {
|
|
||||||
&self.transform
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the style for the current render scope.
|
|
||||||
pub fn set_style(&mut self, style: Style) {
|
|
||||||
self.style = style;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets a mutable reference to the style.
|
|
||||||
pub fn get_style(&mut self) -> &mut Style {
|
|
||||||
&mut self.style
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Debug for RenderScope {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(f, "RenderScope")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+162
-49
@@ -1,100 +1,213 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
any::Any,
|
||||||
fmt::{Debug, Display, Formatter, Result as FmtResult},
|
fmt::{Debug, Display, Formatter, Result as FmtResult},
|
||||||
ops::{Deref, DerefMut},
|
ops::{Deref, DerefMut},
|
||||||
sync::{Arc, Mutex, MutexGuard},
|
sync::{Arc, Mutex, MutexGuard},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Trait for tracking dependencies and reactivity.
|
use crate::prelude::Context;
|
||||||
pub trait DependencyHandler: std::fmt::Debug + Send + Sync {
|
|
||||||
/// Called when a dependent is registered.
|
#[derive(Clone)]
|
||||||
fn add(&self);
|
pub struct HookEffect(Arc<Mutex<dyn FnMut() + Send + Sync>>);
|
||||||
/// Returns `true` if the state has changed since the last check.
|
|
||||||
fn check(&self) -> bool;
|
#[derive(Debug)]
|
||||||
|
pub struct State<T> {
|
||||||
|
value: Arc<Mutex<T>>,
|
||||||
|
dependents: Arc<Mutex<Vec<HookEffect>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Inner<'a, T> {
|
||||||
|
value: MutexGuard<'a, T>,
|
||||||
|
dependents: Arc<Mutex<Vec<HookEffect>>>,
|
||||||
|
updated: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct State<T> {
|
pub struct Mount(Arc<Mutex<bool>>, Arc<Mutex<Vec<HookEffect>>>);
|
||||||
inner: Arc<Mutex<Inner<T>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Inner<T> {
|
|
||||||
value: T,
|
|
||||||
dependencies: usize,
|
|
||||||
changed: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn use_state<T>(v: T) -> State<T> {
|
pub fn use_state<T>(v: T) -> State<T> {
|
||||||
State {
|
State {
|
||||||
inner: Arc::new(Mutex::new(Inner {
|
value: Arc::new(Mutex::new(v)),
|
||||||
value: v,
|
dependents: Arc::new(Mutex::new(Vec::new())),
|
||||||
dependencies: 0,
|
|
||||||
changed: 0,
|
|
||||||
})),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Clone> State<T> {
|
impl<T: Clone> State<T> {
|
||||||
/// Gets the cloned value, recommended for preventing deadlocks
|
/// Gets the cloned value, recommended for preventing deadlocks
|
||||||
pub fn get_dl(&self) -> T {
|
pub fn get_dl(&self) -> T {
|
||||||
self.inner.lock().unwrap().value.clone()
|
self.value.lock().unwrap().clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> State<T> {
|
impl<T> State<T> {
|
||||||
/// Gets a lock on the state for read/write access.
|
/// Gets a lock on the state for read/write access.
|
||||||
pub fn get(&self) -> MutexGuard<'_, Inner<T>> {
|
pub fn get(&self) -> Inner<'_, T> {
|
||||||
self.inner.lock().unwrap()
|
Inner {
|
||||||
|
value: self.value.lock().unwrap(),
|
||||||
|
dependents: self.dependents.clone(),
|
||||||
|
updated: false,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the value and marks it as changed.
|
/// Sets the value and marks it as changed.
|
||||||
pub fn set(&self, v: T) {
|
pub fn set(&self, v: T) {
|
||||||
let mut inner = self.inner.lock().unwrap();
|
*self.value.lock().unwrap() = v;
|
||||||
inner.value = v;
|
self.update();
|
||||||
inner.changed = inner.dependencies;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Marks the state as updated.
|
|
||||||
pub fn update(&self) {
|
pub fn update(&self) {
|
||||||
let mut inner = self.inner.lock().unwrap();
|
for d in self.dependents.lock().unwrap().iter() {
|
||||||
inner.changed = inner.dependencies;
|
d.call();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Debug + Send + Sync> DependencyHandler for State<T> {
|
|
||||||
fn check(&self) -> bool {
|
|
||||||
let mut inner = self.inner.lock().unwrap();
|
|
||||||
let i = inner.changed > 0;
|
|
||||||
if i {
|
|
||||||
inner.changed -= 1;
|
|
||||||
}
|
|
||||||
i
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add(&self) {
|
pub fn clone(&self) -> Self {
|
||||||
let mut inner = self.inner.lock().unwrap();
|
Self {
|
||||||
inner.dependencies += 1;
|
dependents: self.dependents.clone(),
|
||||||
|
value: self.value.clone(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Display> Display for State<T> {
|
impl<T: Display> Display for State<T> {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||||
let inner = self.inner.lock().unwrap();
|
write!(f, "{}", self.value.lock().unwrap())
|
||||||
write!(f, "{}", inner.value)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Deref for Inner<T> {
|
impl Debug for HookEffect {
|
||||||
type Target = T;
|
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||||
|
write!(f, "HookEffect")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HookEffect {
|
||||||
|
pub fn new<F: Fn() + Send + Sync + 'static>(f: F) -> Self {
|
||||||
|
Self(Arc::new(Mutex::new(f)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn call(&self) {
|
||||||
|
(self.0.lock().unwrap())()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Drop for Inner<'_, T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if self.updated {
|
||||||
|
for d in self.dependents.lock().unwrap().iter() {
|
||||||
|
d.call();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for Inner<'_, T> {
|
||||||
|
type Target = T;
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
&self.value
|
&self.value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> DerefMut for Inner<T> {
|
impl<T> DerefMut for Inner<'_, T> {
|
||||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
self.changed = self.dependencies;
|
self.updated = true;
|
||||||
&mut self.value
|
&mut self.value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub trait HookDependency {
|
||||||
|
fn on_update(&self, hook: HookEffect);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> HookDependency for State<T> {
|
||||||
|
fn on_update(&self, hook: HookEffect) {
|
||||||
|
self.dependents.lock().unwrap().push(hook);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HookDependency for Mount {
|
||||||
|
fn on_update(&self, hook: HookEffect) {
|
||||||
|
if *self.0.lock().unwrap() {
|
||||||
|
hook.call();
|
||||||
|
} else {
|
||||||
|
self.1.lock().unwrap().push(hook);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mount {
|
||||||
|
pub fn mount(&self) {
|
||||||
|
*self.0.lock().unwrap() = true;
|
||||||
|
for hook_effect in self.1.lock().unwrap().iter() {
|
||||||
|
hook_effect.call();
|
||||||
|
}
|
||||||
|
self.1.lock().unwrap().clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn use_effect<F: FnMut() + Send + Sync + 'static>(f: F, dependencies: &[&dyn HookDependency]) {
|
||||||
|
let f = Arc::new(Mutex::new(f));
|
||||||
|
let hook = HookEffect(Arc::new(Mutex::new({
|
||||||
|
let f = f.clone();
|
||||||
|
move || {
|
||||||
|
let f = f.clone();
|
||||||
|
std::thread::spawn(move || (f.lock().unwrap())());
|
||||||
|
}
|
||||||
|
})));
|
||||||
|
|
||||||
|
for d in dependencies {
|
||||||
|
d.on_update(hook.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn use_mount() -> Mount {
|
||||||
|
Mount(Arc::new(Mutex::new(true)), Arc::new(Mutex::new(Vec::new())))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn use_mount_manual() -> Mount {
|
||||||
|
Mount(
|
||||||
|
Arc::new(Mutex::new(false)),
|
||||||
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn use_sync_state<
|
||||||
|
T: Send + Sync + 'static,
|
||||||
|
E: Any + 'static,
|
||||||
|
D: Fn(&E) -> T + Send + Sync + 'static,
|
||||||
|
>(
|
||||||
|
cx: &Arc<Context>,
|
||||||
|
v: T,
|
||||||
|
decoder: D,
|
||||||
|
) -> State<T> {
|
||||||
|
let state = use_state(v);
|
||||||
|
|
||||||
|
cx.on_event({
|
||||||
|
let state = state.clone();
|
||||||
|
move |_, v: &E| state.set(decoder(v))
|
||||||
|
});
|
||||||
|
|
||||||
|
state
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn use_sync_effect<
|
||||||
|
T: Send + Sync + 'static,
|
||||||
|
Ev: 'static,
|
||||||
|
E: Fn(&State<T>) -> Ev + Send + Sync + 'static,
|
||||||
|
>(
|
||||||
|
cx: &Arc<Context>,
|
||||||
|
state: &State<T>,
|
||||||
|
encoder: E,
|
||||||
|
deps: &[&dyn HookDependency],
|
||||||
|
) {
|
||||||
|
use_effect(
|
||||||
|
{
|
||||||
|
let state = state.clone();
|
||||||
|
let cx = cx.clone();
|
||||||
|
move || {
|
||||||
|
cx.emit_event(&encoder(&state));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
deps,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
-228
@@ -1,228 +0,0 @@
|
|||||||
//! Layout and style definitions for OSUI widgets.
|
|
||||||
//!
|
|
||||||
//! This module defines the structures used to manage rendering geometry (`Transform`, `RawTransform`),
|
|
||||||
//! position and size enums (`Position`, `Dimension`), and styling (`Style`, `Background`, etc.).
|
|
||||||
//!
|
|
||||||
//! These types are used internally by components to calculate layout and control their appearance.
|
|
||||||
|
|
||||||
use crate::component;
|
|
||||||
|
|
||||||
/// Resolved layout information for a widget after layout calculations.
|
|
||||||
///
|
|
||||||
/// This struct holds concrete values for position (`x`, `y`), dimensions
|
|
||||||
/// (`width`, `height`), and padding (`px`, `py`).
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct RawTransform {
|
|
||||||
pub x: u16,
|
|
||||||
pub y: u16,
|
|
||||||
pub width: u16,
|
|
||||||
pub height: u16,
|
|
||||||
pub px: u16,
|
|
||||||
pub py: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Horizontal or vertical position relative to a parent container.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum Position {
|
|
||||||
/// Fixed position in cells from the origin.
|
|
||||||
Const(u16),
|
|
||||||
/// Centered in the parent.
|
|
||||||
Center,
|
|
||||||
/// Aligned to the end (right or bottom) of the parent.
|
|
||||||
End,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sizing rule for width or height.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum Dimension {
|
|
||||||
/// Fills the available space from the parent.
|
|
||||||
Full,
|
|
||||||
/// Automatically sized to fit content.
|
|
||||||
Content,
|
|
||||||
/// Fixed size in cells.
|
|
||||||
Const(u16),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Background appearance for a widget.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum Background {
|
|
||||||
/// Transparent / no background.
|
|
||||||
NoBackground,
|
|
||||||
/// Draws a basic outline using the given color.
|
|
||||||
Outline(u32),
|
|
||||||
/// Draws a rounded outline using the given color.
|
|
||||||
RoundedOutline(u32),
|
|
||||||
/// Fills the background with the specified color.
|
|
||||||
Solid(u32),
|
|
||||||
}
|
|
||||||
|
|
||||||
component!(Transform {
|
|
||||||
pub x: Position,
|
|
||||||
pub y: Position,
|
|
||||||
pub mx: i32,
|
|
||||||
pub my: i32,
|
|
||||||
pub px: u16,
|
|
||||||
pub py: u16,
|
|
||||||
pub width: Dimension,
|
|
||||||
pub height: Dimension,
|
|
||||||
});
|
|
||||||
|
|
||||||
component!(Style {
|
|
||||||
pub background: Background,
|
|
||||||
pub foreground: Option<u32>,
|
|
||||||
});
|
|
||||||
|
|
||||||
impl Style {
|
|
||||||
/// Creates a style with no background or foreground.
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
background: Background::NoBackground,
|
|
||||||
foreground: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Transform {
|
|
||||||
/// Creates a default transform with top-left alignment and content sizing.
|
|
||||||
pub fn new() -> Transform {
|
|
||||||
Transform {
|
|
||||||
x: Position::Const(0),
|
|
||||||
y: Position::Const(0),
|
|
||||||
mx: 0,
|
|
||||||
my: 0,
|
|
||||||
px: 0,
|
|
||||||
py: 0,
|
|
||||||
width: Dimension::Content,
|
|
||||||
height: Dimension::Content,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Shortcut for centering both horizontally and vertically.
|
|
||||||
pub fn center() -> Transform {
|
|
||||||
Transform {
|
|
||||||
x: Position::Center,
|
|
||||||
y: Position::Center,
|
|
||||||
mx: 0,
|
|
||||||
my: 0,
|
|
||||||
px: 0,
|
|
||||||
py: 0,
|
|
||||||
width: Dimension::Content,
|
|
||||||
height: Dimension::Content,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Aligns the widget to the bottom of its parent.
|
|
||||||
pub fn bottom(mut self) -> Self {
|
|
||||||
self.y = Position::End;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Aligns the widget to the right of its parent.
|
|
||||||
pub fn right(mut self) -> Self {
|
|
||||||
self.x = Position::End;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds margin (offset) from parent edge.
|
|
||||||
pub fn margin(mut self, x: i32, y: i32) -> Self {
|
|
||||||
self.mx = x;
|
|
||||||
self.my = y;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds internal spacing (padding) around content.
|
|
||||||
pub fn padding(mut self, x: u16, y: u16) -> Self {
|
|
||||||
self.px = x;
|
|
||||||
self.py = y;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets constant dimensions.
|
|
||||||
pub fn dimensions(mut self, width: u16, height: u16) -> Self {
|
|
||||||
self.width = Dimension::Const(width);
|
|
||||||
self.height = Dimension::Const(height);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolves `Dimension` rules into absolute values for the given parent size.
|
|
||||||
pub fn use_dimensions(&self, parent_width: u16, parent_height: u16, raw: &mut RawTransform) {
|
|
||||||
self.width.use_dimension(parent_width, &mut raw.width);
|
|
||||||
self.height.use_dimension(parent_height, &mut raw.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolves `Position` rules into absolute positions for the given parent size.
|
|
||||||
pub fn use_position(&self, parent_width: u16, parent_height: u16, raw: &mut RawTransform) {
|
|
||||||
self.x
|
|
||||||
.use_position(raw.width, parent_width, self.mx, &mut raw.x);
|
|
||||||
self.y
|
|
||||||
.use_position(raw.height, parent_height, self.my, &mut raw.y);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RawTransform {
|
|
||||||
/// Creates a new transform with all fields set to 0.
|
|
||||||
pub fn new() -> RawTransform {
|
|
||||||
RawTransform {
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
width: 0,
|
|
||||||
height: 0,
|
|
||||||
px: 0,
|
|
||||||
py: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Dimension {
|
|
||||||
/// Applies a dimension rule to determine a final size.
|
|
||||||
pub fn use_dimension(&self, parent: u16, r: &mut u16) {
|
|
||||||
match self {
|
|
||||||
Self::Full => *r = parent,
|
|
||||||
Self::Content => {}
|
|
||||||
Self::Const(n) => *r = *n,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Position {
|
|
||||||
/// Applies a position rule to determine a final coordinate, based on size and parent.
|
|
||||||
pub fn use_position(&self, size: u16, parent: u16, m: i32, r: &mut u16) {
|
|
||||||
let base = match self {
|
|
||||||
Self::Center => {
|
|
||||||
if parent < size {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
(parent - size) / 2
|
|
||||||
}
|
|
||||||
Self::Const(n) => *n,
|
|
||||||
Self::End => {
|
|
||||||
if parent < size {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
parent - size
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let adjusted = if m >= 0 {
|
|
||||||
base.checked_add(m as u16)
|
|
||||||
} else {
|
|
||||||
base.checked_sub((-m) as u16)
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(val) = adjusted {
|
|
||||||
*r = val;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<u16> for Position {
|
|
||||||
fn from(value: u16) -> Self {
|
|
||||||
Self::Const(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<u16> for Dimension {
|
|
||||||
fn from(value: u16) -> Self {
|
|
||||||
Self::Const(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-122
@@ -1,122 +0,0 @@
|
|||||||
//! The `utils` module provides utility functions for terminal manipulation
|
|
||||||
//! and string operations, designed to enhance terminal-based applications.
|
|
||||||
|
|
||||||
use std::io::{self, Write};
|
|
||||||
|
|
||||||
/// Clears the terminal screen and moves the cursor to the top-left corner.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```
|
|
||||||
/// utils::clear().unwrap();
|
|
||||||
/// ```
|
|
||||||
pub fn clear() -> io::Result<()> {
|
|
||||||
print!("\x1B[2J\x1B[H");
|
|
||||||
std::io::stdout().flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hides the terminal cursor.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```
|
|
||||||
/// utils::hide_cursor().unwrap();
|
|
||||||
/// ```
|
|
||||||
pub fn hide_cursor() -> io::Result<()> {
|
|
||||||
print!("\x1b[?25l");
|
|
||||||
std::io::stdout().flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Shows the terminal cursor.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```
|
|
||||||
/// utils::show_cursor().unwrap();
|
|
||||||
/// ```
|
|
||||||
pub fn show_cursor() -> io::Result<()> {
|
|
||||||
print!("\x1B[?25h");
|
|
||||||
std::io::stdout().flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Flushes the terminal's stdout buffer.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A `io::Result<()>` indicating whether the operation succeeded.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```
|
|
||||||
/// utils::flush().unwrap();
|
|
||||||
/// ```
|
|
||||||
pub fn flush() -> io::Result<()> {
|
|
||||||
std::io::stdout().flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Calculates the width and height of a string when rendered in a terminal.
|
|
||||||
///
|
|
||||||
/// # Arguments
|
|
||||||
/// - `s`: The input string.
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// A tuple `(u16, u16)` where:
|
|
||||||
/// - The first value is the maximum width of the string in characters.
|
|
||||||
/// - The second value is the height of the string in lines.
|
|
||||||
///
|
|
||||||
/// # Example
|
|
||||||
/// ```
|
|
||||||
/// let (width, height) = utils::str_size("Hello\nWorld!");
|
|
||||||
/// assert_eq!((5, 2), (width, height));
|
|
||||||
/// ```
|
|
||||||
pub fn str_size(s: &str) -> (u16, u16) {
|
|
||||||
let mut height = 1;
|
|
||||||
let mut max_width = 0;
|
|
||||||
let mut current_width = 0;
|
|
||||||
|
|
||||||
for b in s.bytes() {
|
|
||||||
if b == b'\n' {
|
|
||||||
height += 1;
|
|
||||||
max_width = max_width.max(current_width);
|
|
||||||
current_width = 0;
|
|
||||||
} else {
|
|
||||||
current_width += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
max_width = max_width.max(current_width);
|
|
||||||
|
|
||||||
(max_width, height)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn hex_ansi(hex: u32) -> String {
|
|
||||||
let r = ((hex >> 16) & 0xFF) as u8;
|
|
||||||
let g = ((hex >> 8) & 0xFF) as u8;
|
|
||||||
let b = (hex & 0xFF) as u8;
|
|
||||||
format!("\x1b[38;2;{r};{g};{b}m")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn hex_ansi_bg(hex: u32) -> String {
|
|
||||||
let r = ((hex >> 16) & 0xFF) as u8;
|
|
||||||
let g = ((hex >> 8) & 0xFF) as u8;
|
|
||||||
let b = (hex & 0xFF) as u8;
|
|
||||||
format!("\x1b[48;2;{r};{g};{b}m")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn print(x: u16, y: u16, text: &str) {
|
|
||||||
for (i, line) in text.lines().enumerate() {
|
|
||||||
print!("\x1b[{};{}H{line}\x1b[0m", y + i as u16 + 1, x + 1);
|
|
||||||
flush().unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn print_liner(x: u16, y: u16, liner: &str, text: &str) {
|
|
||||||
for (i, line) in text.lines().enumerate() {
|
|
||||||
print!("\x1b[{};{}H{liner}{line}\x1b[0m", y + i as u16 + 1, x + 1);
|
|
||||||
flush().unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-362
@@ -1,362 +0,0 @@
|
|||||||
//! Core widget infrastructure for OSUI.
|
|
||||||
//!
|
|
||||||
//! This module defines the traits and types that power the widget system, including:
|
|
||||||
//! - `Element` and `Component`: building blocks for renderable and state-carrying objects
|
|
||||||
//! - `Widget`: container type for wrapping elements and components
|
|
||||||
//! - `StaticWidget` and `DynWidget`: concrete widget implementations
|
|
||||||
//! - Dependency tracking and reactive updates for dynamic widgets
|
|
||||||
|
|
||||||
use std::{
|
|
||||||
any::{Any, TypeId},
|
|
||||||
collections::HashMap,
|
|
||||||
sync::{Arc, Mutex, MutexGuard},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
prelude::{Event, Handler},
|
|
||||||
render_scope::RenderScope,
|
|
||||||
state::DependencyHandler,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// A trait object for any renderable UI element.
|
|
||||||
pub type BoxedElement = Box<dyn Element + Send + Sync>;
|
|
||||||
|
|
||||||
/// A trait object for any component attached to a widget.
|
|
||||||
pub type BoxedComponent = Box<dyn Component + Send + Sync>;
|
|
||||||
|
|
||||||
/// Core trait for anything that can be rendered in the UI.
|
|
||||||
///
|
|
||||||
/// Elements are responsible for their own rendering logic and can define hooks
|
|
||||||
/// for lifecycle events and child rendering.
|
|
||||||
pub trait Element: Send + Sync {
|
|
||||||
/// Called to perform rendering for the element.
|
|
||||||
#[allow(unused)]
|
|
||||||
fn render(&mut self, scope: &mut RenderScope) {}
|
|
||||||
|
|
||||||
/// Called after rendering, for follow-up logic or cleanup.
|
|
||||||
#[allow(unused)]
|
|
||||||
fn after_render(&mut self, scope: &mut RenderScope) {}
|
|
||||||
|
|
||||||
/// Called to draw child widgets, if any.
|
|
||||||
#[allow(unused)]
|
|
||||||
fn draw_child(&mut self, element: &Arc<Widget>) {}
|
|
||||||
|
|
||||||
#[allow(unused)]
|
|
||||||
fn event(&mut self, event: &dyn Event) {}
|
|
||||||
|
|
||||||
/// Returns a type-erased reference to this object.
|
|
||||||
fn as_any(&self) -> &dyn Any;
|
|
||||||
|
|
||||||
/// Returns a mutable type-erased reference to this object.
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn Any;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Optional trait for state or metadata attached to widgets.
|
|
||||||
///
|
|
||||||
/// Components can be used to store data such as layout style,
|
|
||||||
/// animation state, bindings, or other logic.
|
|
||||||
pub trait Component: Send + Sync {
|
|
||||||
fn as_any(&self) -> &dyn Any;
|
|
||||||
fn as_any_mut(&mut self) -> &mut dyn Any;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Container for a widget during initial construction.
|
|
||||||
///
|
|
||||||
/// Holds the root element and any associated components.
|
|
||||||
pub struct WidgetLoad(BoxedElement, HashMap<TypeId, BoxedComponent>);
|
|
||||||
|
|
||||||
/// A widget with fixed content and no dynamic behavior.
|
|
||||||
pub struct StaticWidget(Mutex<BoxedElement>, Mutex<HashMap<TypeId, BoxedComponent>>);
|
|
||||||
|
|
||||||
/// A widget with dynamic content and dependency tracking.
|
|
||||||
///
|
|
||||||
/// This widget supports reactive updates and can be rebuilt using
|
|
||||||
/// a provided `FnMut()` function when dependencies change.
|
|
||||||
pub struct DynWidget(
|
|
||||||
Mutex<BoxedElement>,
|
|
||||||
Mutex<HashMap<TypeId, BoxedComponent>>,
|
|
||||||
Mutex<Box<dyn FnMut() -> WidgetLoad + Send + Sync>>,
|
|
||||||
Mutex<Vec<Box<dyn DependencyHandler>>>,
|
|
||||||
Mutex<Option<Box<dyn FnMut(WidgetLoad) -> WidgetLoad + Send + Sync>>>,
|
|
||||||
);
|
|
||||||
|
|
||||||
/// A reference-counted wrapper around either a static or dynamic widget.
|
|
||||||
///
|
|
||||||
/// Use `Arc<Widget>` as the standard way to store and pass around widgets in the UI tree.
|
|
||||||
pub enum Widget {
|
|
||||||
Static(StaticWidget),
|
|
||||||
Dynamic(DynWidget),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WidgetLoad {
|
|
||||||
/// Creates a new `WidgetLoad` with a given root element.
|
|
||||||
pub fn new<E: Element + 'static>(e: E) -> Self {
|
|
||||||
Self(Box::new(e), HashMap::new())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Attaches a component if one of its type doesn't already exist.
|
|
||||||
pub fn component<C: Component + 'static>(mut self, c: C) -> Self {
|
|
||||||
self.1.entry(c.type_id()).or_insert_with(|| Box::new(c));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Replaces any existing component of the same type.
|
|
||||||
pub fn set_component<C: Component + 'static>(mut self, c: C) -> Self {
|
|
||||||
self.1.insert(c.type_id(), Box::new(c));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Attempts to retrieve a component of the given type.
|
|
||||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
|
||||||
self.1
|
|
||||||
.get(&TypeId::of::<C>())
|
|
||||||
.and_then(|c| c.as_any().downcast_ref::<C>())
|
|
||||||
.map(|c| c.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Widget {
|
|
||||||
pub fn new_static(e: BoxedElement) -> Self {
|
|
||||||
Self::Static(StaticWidget(Mutex::new(e), Mutex::new(HashMap::new())))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_dyn<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(mut e: F) -> Self {
|
|
||||||
let wl = e();
|
|
||||||
Self::Dynamic(DynWidget(
|
|
||||||
Mutex::new(wl.0),
|
|
||||||
Mutex::new(wl.1),
|
|
||||||
Mutex::new(Box::new(e)),
|
|
||||||
Mutex::new(Vec::new()),
|
|
||||||
Mutex::new(None),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Widget {
|
|
||||||
pub fn get_elem(&self) -> MutexGuard<BoxedElement> {
|
|
||||||
match self {
|
|
||||||
Widget::Static(w) => w.get_elem(),
|
|
||||||
Widget::Dynamic(w) => w.get_elem(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn after_render(&self) {
|
|
||||||
match self {
|
|
||||||
Widget::Static(w) => w.after_render(),
|
|
||||||
Widget::Dynamic(w) => w.after_render(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
|
|
||||||
match &**self {
|
|
||||||
Widget::Static(w) => {
|
|
||||||
w.component(c);
|
|
||||||
}
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.component(c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
|
|
||||||
match &**self {
|
|
||||||
Widget::Static(w) => {
|
|
||||||
w.set_component(c);
|
|
||||||
}
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.set_component(c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
|
||||||
match self {
|
|
||||||
Widget::Static(w) => w.get(),
|
|
||||||
Widget::Dynamic(w) => w.get(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn inject<F: FnMut(WidgetLoad) -> WidgetLoad + 'static + Send + Sync>(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
mut f: F,
|
|
||||||
) {
|
|
||||||
match &**self {
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.inject(f);
|
|
||||||
}
|
|
||||||
Widget::Static(w) => {
|
|
||||||
let wl = WidgetLoad::new(String::new());
|
|
||||||
w.1.lock().unwrap().extend(f(wl).1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh(self: &Arc<Self>) {
|
|
||||||
match &**self {
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.refresh();
|
|
||||||
}
|
|
||||||
Widget::Static(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn auto_refresh(self: &Arc<Self>) {
|
|
||||||
match &**self {
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.auto_refresh();
|
|
||||||
}
|
|
||||||
Widget::Static(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn dependency<D: DependencyHandler + 'static>(self: &Arc<Self>, d: D) -> &Arc<Self> {
|
|
||||||
match &**self {
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.dependency(d);
|
|
||||||
}
|
|
||||||
Widget::Static(_) => {}
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn dependency_box(self: &Arc<Self>, d: Box<dyn DependencyHandler>) -> &Arc<Self> {
|
|
||||||
match &**self {
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.dependency_box(d);
|
|
||||||
}
|
|
||||||
Widget::Static(_) => {}
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn event<E: Event + Clone + 'static>(self: &Arc<Self>, e: &E) {
|
|
||||||
if let Some(wrapper) = self.get::<Handler<E>>() {
|
|
||||||
wrapper.call(self, e);
|
|
||||||
}
|
|
||||||
|
|
||||||
match &**self {
|
|
||||||
Widget::Dynamic(w) => {
|
|
||||||
w.get_elem().event(e);
|
|
||||||
}
|
|
||||||
Widget::Static(w) => {
|
|
||||||
w.get_elem().event(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StaticWidget {
|
|
||||||
fn after_render(&self) {}
|
|
||||||
fn get_elem(&self) -> MutexGuard<BoxedElement> {
|
|
||||||
self.0.lock().unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StaticWidget {
|
|
||||||
pub fn new(e: BoxedElement) -> Self {
|
|
||||||
Self(Mutex::new(e), Mutex::new(HashMap::new()))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn component<C: Component + 'static>(&self, c: C) {
|
|
||||||
self.1
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.entry(c.type_id())
|
|
||||||
.or_insert_with(|| Box::new(c));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_component<C: Component + 'static>(&self, c: C) {
|
|
||||||
self.1.lock().unwrap().insert(c.type_id(), Box::new(c));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
|
||||||
self.1
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.get(&TypeId::of::<C>())
|
|
||||||
.and_then(|c| c.as_any().downcast_ref::<C>())
|
|
||||||
.map(Clone::clone)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DynWidget {
|
|
||||||
fn after_render(&self) {}
|
|
||||||
fn get_elem(&self) -> MutexGuard<BoxedElement> {
|
|
||||||
self.0.lock().unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DynWidget {
|
|
||||||
pub fn new<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(mut e: F) -> Self {
|
|
||||||
let wl = e();
|
|
||||||
Self(
|
|
||||||
Mutex::new(wl.0),
|
|
||||||
Mutex::new(wl.1),
|
|
||||||
Mutex::new(Box::new(e)),
|
|
||||||
Mutex::new(Vec::new()),
|
|
||||||
Mutex::new(None),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Replace or modify the widget's structure on reload and init.
|
|
||||||
pub fn inject<F: FnMut(WidgetLoad) -> WidgetLoad + 'static + Send + Sync>(&self, f: F) {
|
|
||||||
*self.4.lock().unwrap() = Some(Box::new(f));
|
|
||||||
self.refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Rebuild the widget's content by re-evaluating the original function.
|
|
||||||
pub fn refresh(&self) {
|
|
||||||
let mut w = (self.2.lock().unwrap())();
|
|
||||||
|
|
||||||
if let Some(we) = &mut *self.4.lock().unwrap() {
|
|
||||||
w = (we)(w);
|
|
||||||
}
|
|
||||||
|
|
||||||
*self.0.lock().unwrap() = w.0;
|
|
||||||
*self.1.lock().unwrap() = w.1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Re-evaluates the widget if any dependency has changed.
|
|
||||||
pub fn auto_refresh(&self) {
|
|
||||||
for d in self.3.lock().unwrap().iter() {
|
|
||||||
if d.check() {
|
|
||||||
self.refresh();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a dependency to this widget.
|
|
||||||
pub fn dependency<D: DependencyHandler + 'static>(&self, d: D) {
|
|
||||||
d.add();
|
|
||||||
self.3.lock().unwrap().push(Box::new(d));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a boxed dependency.
|
|
||||||
pub fn dependency_box(&self, d: Box<dyn DependencyHandler>) {
|
|
||||||
d.add();
|
|
||||||
self.3.lock().unwrap().push(d);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn component<C: Component + 'static>(&self, c: C) {
|
|
||||||
self.1
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.entry(c.type_id())
|
|
||||||
.or_insert_with(|| Box::new(c));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_component<C: Component + 'static>(&self, c: C) {
|
|
||||||
self.1.lock().unwrap().insert(c.type_id(), Box::new(c));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
|
||||||
self.1
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.get(&TypeId::of::<C>())
|
|
||||||
.and_then(|c| c.as_any().downcast_ref::<C>())
|
|
||||||
.map(Clone::clone)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user