143 Commits
Author SHA1 Message Date
selimaj-dev 506ccae049 State syncing 2026-01-26 17:27:47 +01:00
selimaj-dev 86e3f4e684 Sync state (param passing) 2026-01-26 16:58:44 +01:00
selimaj-dev 89b460697f Any event 2026-01-26 09:38:36 +01:00
selimaj-dev bd53e6450c use effect instead of event 2026-01-26 09:34:23 +01:00
selimaj-dev 083812458b Children clear for loop 2026-01-25 21:12:34 +01:00
selimaj-dev 4364177538 Text @position 2026-01-25 21:11:42 +01:00
selimaj-dev 98598bec15 Initial dynamic render 2026-01-25 20:46:26 +01:00
selimaj-dev eb702dce45 RSX dependency 2026-01-25 20:40:24 +01:00
selimaj-dev 229353f5f0 RSX dependency 2026-01-25 20:39:17 +01:00
selimaj-dev 04a69b138a RSX For loop 2026-01-25 20:12:47 +01:00
selimaj-dev 993a790da7 If statement rsx 2026-01-25 20:00:21 +01:00
selimaj-dev ecc1172737 Rsx scope child 2026-01-25 19:22:36 +01:00
selimaj-dev a9ecc8da8b working Rsx 2026-01-25 18:58:24 +01:00
selimaj-dev f6a4bbd8ac Frontend structure 2026-01-25 18:38:07 +01:00
selimaj-dev 4afe1c24c2 Added use_mount 2026-01-25 17:22:40 +01:00
Klesti Selimaj b50ca3263b Merge pull request #38 from osui-rs/render-scoping
Render scoping
2026-01-25 17:15:04 +01:00
selimaj-dev 6b3e9239c9 Scope view 2026-01-25 02:27:36 +01:00
selimaj-dev 470512a542 Dynamic scoping with for loop 2026-01-25 02:22:16 +01:00
selimaj-dev 6e481862ec Dynamic scoping with if statement 2026-01-25 02:17:08 +01:00
selimaj-dev 05a390b10f Dynamic scoping 2026-01-25 00:30:53 +01:00
selimaj-dev 926405a863 Dynamic scoping 2026-01-24 21:38:45 +01:00
selimaj-dev 9953e4a0bc Render position 2026-01-24 17:46:33 +01:00
selimaj-dev 8f0712d4f8 Event passing 2026-01-24 17:31:58 +01:00
selimaj-dev 9d55dacde2 Context children 2026-01-24 17:22:59 +01:00
selimaj-dev abe37686d8 Refresh on children 2026-01-24 16:40:03 +01:00
selimaj-dev 02f3aea4e3 Fixed refresh 2026-01-24 16:01:22 +01:00
selimaj-dev 33370287b2 Renderer 2026-01-24 14:49:47 +01:00
selimaj-dev 0f12a371e5 Renderer 2026-01-24 14:47:53 +01:00
selimaj-dev 1f9bf48bb4 View render 2026-01-24 14:37:19 +01:00
selimaj-dev 49bb99fedb Simple test 2026-01-24 14:26:04 +01:00
selimaj-dev 979af999e4 Simple renderer 2026-01-24 14:17:05 +01:00
selimaj-dev 0515087f0d Renderer 2026-01-24 10:44:30 +01:00
selimaj-dev 2a62e53ed5 Engine 2026-01-24 01:00:21 +01:00
selimaj-dev c2b9bb3aa1 DrawContext size 2026-01-24 00:42:54 +01:00
selimaj-dev 0a026c4ee7 View 2026-01-24 00:28:43 +01:00
selimaj-dev 15ff801cb0 Emit event threaded 2025-11-23 18:01:21 +01:00
selimaj-dev 538cc8731f Improved state mangement 2025-11-23 11:23:28 +01:00
selimaj-dev b326fc48ed Improved state management 2025-11-23 11:10:07 +01:00
selimaj-dev 8740bbee89 Working event handling 2025-11-23 10:37:20 +01:00
selimaj-dev 22d02e7d1a Multithreaded 2025-11-23 09:58:01 +01:00
selimaj-dev 0cefbaa223 Testing 2025-11-20 23:23:01 +01:00
selimaj-dev b57fffe9b7 Testing 2025-11-20 23:15:31 +01:00
selimaj-dev 4d2f0d7b9d State management 2025-11-20 17:17:18 +01:00
selimaj-dev ff351caee0 Testing new structure 2025-11-20 17:10:12 +01:00
selimaj-dev e4110976cd Testing new structure 2025-11-20 16:57:14 +01:00
selimaj-dev 1fbff7a0bc Testing new structure 2025-11-19 09:14:03 +01:00
selimaj-dev 6e8ca5535e Testing new structure 2025-11-18 20:17:02 +01:00
selimaj-dev e031f9bcef Testing new structure 2025-11-18 20:04:14 +01:00
Klesti Selimaj c6d11315d6 Merge pull request #36 from osui-rs/refactor
Refactor
2025-11-02 12:31:59 +01:00
selimaj-dev 68d00be96c Simple velocity example 2025-11-02 10:49:25 +01:00
selimaj-dev f5d1b42db4 Velocity element 2025-11-02 10:26:15 +01:00
selimaj-dev 63ed7b8da4 Y offset fix on print 2025-11-02 09:16:03 +01:00
selimaj-dev 98b2a4e667 Outline position fix 2025-11-02 09:10:34 +01:00
selimaj-dev e4b905d085 Refactored render scope 2025-11-02 09:00:33 +01:00
Klesti Selimaj 1d6ce1506e Merge pull request #34 from osui-rs/scroll
Scroll
2025-11-01 23:34:04 +01:00
selimaj-dev 0e3c1ccafe Fixed bad scissor 2025-11-01 23:19:22 +01:00
selimaj-dev dbd16956dd Seperated row and column flex 2025-11-01 22:50:19 +01:00
selimaj-dev c91a473263 Added auth example 2025-11-01 22:47:27 +01:00
selimaj-dev 6424ad3390 Small change in iter 2025-11-01 16:58:10 +01:00
selimaj-dev 23edb6c917 Mouse input 2025-11-01 15:30:03 +01:00
selimaj-dev 72e8df007e Scroll 2025-11-01 15:14:54 +01:00
selimaj-dev a2350f10f5 Dynamic flex size 2025-11-01 13:30:41 +01:00
selimaj-dev 2d41f3b50b Fixed padding 2025-11-01 13:02:10 +01:00
selimaj-dev 5cb6d341af Even width and height comparisons 2025-11-01 13:01:44 +01:00
selimaj-dev f41a4936f9 Fixed paginator render 2025-11-01 12:45:46 +01:00
selimaj-dev dbb8a0e01a Fixed area rendering and merging issues 2025-11-01 12:40:30 +01:00
selimaj-dev fd8e466830 Parent transform 2025-11-01 11:56:55 +01:00
selimaj-dev 29432a939b Paginator 2025-11-01 09:48:04 +01:00
selimaj-dev 9d4b247b2a Working area stop 2025-11-01 09:25:05 +01:00
selimaj-dev 916818f915 1k commits 🥳 (Fixed delete key not working in input) 2025-09-05 20:26:37 +02:00
Leo Codes 5cf59f751d Merge pull request #32 from osui-rs/use-effect
Added a `run!` macro for useEffect behavior
2025-08-14 09:43:30 -04:00
selimaj-dev c460e073a7 Updated the run macro #31 #30 2025-08-14 15:42:21 +02:00
selimaj-dev f51182b2b1 Updated the run macro #30 #31 2025-08-14 15:40:39 +02:00
selimaj-dev 6100023a2a Added a run macro with useEffect like properties #30 2025-08-14 05:01:03 +02:00
Leo Codes 3d9aa35964 Merge pull request #29 from osui-rs/iteration-patch
Added iteration and improved examples
2025-08-12 23:43:39 -04:00
selimaj-dev 9a03f241d8 Added rsx iteration 2025-08-12 23:40:56 -04:00
selimaj-dev fde8ad17d6 added Iterator 2025-08-12 23:18:35 -04:00
selimaj-dev e0cf149790 Updated examples with a few small changes to resolve warnings 2025-08-12 21:12:54 -04:00
Leo Codes 1e590597f3 Merge pull request #28 from osui-rs/render-refactor
Render refactor
2025-08-10 14:46:47 -04:00
selimaj-dev 935f18178e changed demo exit key from q to escape 2025-08-10 13:45:45 -05:00
selimaj-dev 20a9d2b216 Improved ghost with paginator 2025-08-09 02:44:17 +02:00
selimaj-dev 3520369e35 Added ghost elements to avoid focusing on them 2025-08-09 02:27:16 +02:00
selimaj-dev c8ebe36d78 Added focus cursor in input 2025-08-08 23:51:15 +02:00
selimaj-dev d3861909e7 added RenderContext 2025-08-08 23:47:21 +02:00
selimaj-dev 1bdbc447ab Merge branch 'render-refactor' of github.com:osui-rs/osui into render-refactor 2025-08-08 23:38:21 +02:00
selimaj-dev e0059585ce Implemented the ElementRenderer for widgets 2025-08-04 12:35:56 -05:00
selimaj-dev b363c81a24 Added a ElementRenderer trait for element renderers 2025-08-04 12:16:23 -05:00
Leo Codes 2fae5c71f8 Merge pull request #27 from osui-rs/elem-nav
Elem nav
2025-08-04 08:25:54 -05:00
selimaj-dev 9868f02c33 Version update to 0.1.1 (for later) 2025-08-04 08:24:35 -05:00
selimaj-dev 896dfb0a36 Added a AlwaysFocused component #26 2025-08-04 08:23:51 -05:00
selimaj-dev 3a5286a54f Added focus #26 2025-08-04 08:16:34 -05:00
selimaj-dev ca4ee54e9d Added after render and render on extension with child handlers #26 2025-08-04 05:58:11 -05:00
selimaj-dev 62e0c1eac1 Added event on Extension #26 2025-08-04 04:50:52 -05:00
selimaj-dev 48397c06fa Added ExtensionContext #26 2025-08-04 04:45:55 -05:00
selimaj-dev 14602f95c8 First widget focus #26 2025-08-04 04:24:41 -05:00
selimaj-dev fbd84f98d3 Added focus on widget #26 2025-08-04 04:17:40 -05:00
selimaj-dev db1de03fbb Refactored widget #26 2025-08-04 04:05:38 -05:00
Leo Codes 6569a9eb20 Merge pull request #25 from osui-rs/more-elements
More elements
2025-08-03 13:25:54 -05:00
selimaj-dev 2c7d3cc80f added .sparkignore 2025-08-03 13:24:21 -05:00
Leo Codes 2383a7b42a Merge pull request #24 from osui-rs/more-elements
More elements
2025-08-03 09:33:06 -05:00
selimaj-dev d59c3d7911 Added a NoRenderRoot component for root only and NoRender doesn't render on child handlers 2025-08-03 09:20:25 -05:00
selimaj-dev 1aa78bc1a4 Fixed input still typing with modifiers like ctrl 2025-08-03 09:11:50 -05:00
selimaj-dev f8f924ce25 Fixed input still typing with modifiers like ctrl 2025-08-03 09:11:04 -05:00
selimaj-dev ea9afb0e64 Added a paginator #19 2025-08-03 09:04:48 -05:00
selimaj-dev 71299046d3 Mutable draw_child so no more mutex needed 2025-08-03 09:04:24 -05:00
selimaj-dev acce51c372 added a input element #19 2025-08-02 17:15:55 -05:00
selimaj-dev ba04a82980 Updated RenderScope with positions 2025-08-02 17:07:09 -05:00
selimaj-dev ec3576e6db Element events #19 2025-08-02 16:26:38 -05:00
Leo Codes e0ae338e15 Merge pull request #23 from osui-rs/foreground-style
Functional foreground #22
2025-08-02 13:15:42 -05:00
selimaj-dev d2757ad7b0 Functional foreground #22 2025-08-02 13:14:51 -05:00
Leo Codes de039fac96 Merge pull request #21 from osui-rs/rsx-patch-args
Rsx patch args
2025-08-02 12:59:23 -05:00
selimaj-dev 2d8755b13c added heading #19 2025-08-02 12:58:45 -05:00
selimaj-dev d9d107bd80 Added rsx element fields #20 2025-08-02 12:19:04 -05:00
selimaj-dev 35dcc4d22c v0.1.0 2025-08-02 11:21:40 -05:00
selimaj-dev 34b5799644 Added a close function #18 2025-08-02 06:58:13 -05:00
selimaj-dev 911968a1cb input handling #17 2025-08-02 06:47:03 -05:00
Leo Codes d00fbb6565 Merge pull request #16 from osui-rs/demos-module
Demos module
2025-08-02 06:17:27 -05:00
selimaj-dev 2892176a76 Square outline demo fix #15 2025-08-02 06:16:09 -05:00
selimaj-dev 36e06732d9 Padding fix for flex 2025-08-02 06:15:24 -05:00
selimaj-dev 3a4c3505ac Padding fix for flex 2025-08-02 06:14:13 -05:00
selimaj-dev 0ccf03de3b Simple demos #15 2025-08-02 06:02:54 -05:00
selimaj-dev 48849c7cc2 use_area instead of draw_rect for div 2025-08-02 05:55:35 -05:00
selimaj-dev 2b0d85549f Simple demo #15 2025-08-02 05:48:57 -05:00
Leo Codes 598ab5b54d Merge pull request #14 from osui-rs/code-cleanup
Code cleanup
2025-08-01 20:36:26 -05:00
selimaj-dev 095aa14b82 document widget.rs (some unfinished) #13 2025-08-01 20:34:32 -05:00
selimaj-dev d1008a69c9 document style.rs #13 2025-08-01 20:29:41 -05:00
selimaj-dev a30afdeb28 document state.rs #13 2025-08-01 20:26:21 -05:00
selimaj-dev 1debb6a576 document render_scope.rs #13 2025-08-01 20:24:43 -05:00
selimaj-dev fc0406e412 document macros.rs #13 2025-08-01 20:23:03 -05:00
selimaj-dev 27580e773a document frontend.rs #13 2025-08-01 20:20:20 -05:00
selimaj-dev a1499064ac document lib #13 2025-08-01 20:16:18 -05:00
selimaj-dev c2563358b6 document lib #13 2025-08-01 20:02:55 -05:00
selimaj-dev b45ef950a1 changed % state dependency to be after the components 2025-08-01 19:47:41 -05:00
selimaj-dev 063c90d986 #13 cleanup frontend and widgets 2025-08-01 19:44:55 -05:00
selimaj-dev da1ecb1f21 #13 cleanup extensions 2025-08-01 19:25:14 -05:00
selimaj-dev 75827260cc cleanup elements #13 2025-08-01 19:24:39 -05:00
Leo Codes 9a91fb3af0 Merge pull request #12 from osui-rs/better-state-management
Better state management
2025-08-01 16:34:26 -05:00
selimaj-dev bbff192788 Updated readme for the new syntax with rsx 2025-08-01 16:33:35 -05:00
selimaj-dev 73e2c214ee Refactored the frontend to work with static widgets #11 2025-08-01 16:32:56 -05:00
selimaj-dev 45db1fb774 Refactored the widget system #11 2025-08-01 16:10:56 -05:00
selimaj-dev af5428a2f3 area draw 2025-08-01 14:46:59 -05:00
selimaj-dev b227f19a9c padding 2025-07-30 01:14:38 +02:00
selimaj-dev ae16c9a69e background 2025-07-30 00:15:40 +02:00
25 changed files with 804 additions and 1479 deletions
+5
View File
@@ -0,0 +1,5 @@
debug
target
github
Cargo.lock
.DS_Store
+3 -3
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "osui" name = "osui"
version = "0.0.9-alpha.2" 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"
@@ -25,6 +24,7 @@ cc = "1.0"
[dependencies] [dependencies]
crossterm = "0.28.1" crossterm = "0.28.1"
figlet-rs = "0.1.5"
[profile.dev] [profile.dev]
opt-level = 1 opt-level = 1
+5 -4
View File
@@ -21,14 +21,15 @@
</p> </p>
```rust ```rust
use osui::{style::Transform, Screen}; use osui::prelude::*;
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {
let screen = Screen::new(); let screen = Screen::new();
screen rsx! {
.draw(format!("Hello, World")) "Hello, World"
.component(Transform::center()); }
.draw(&screen);
screen.run() screen.run()
} }
+68
View File
@@ -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())
}
+199
View File
@@ -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));
}
}
-70
View File
@@ -1,70 +0,0 @@
use std::sync::{Arc, Mutex};
use crate::{
widget::{Element, Widget},
NoRender,
};
pub struct Div {
color: u32,
children: Mutex<Vec<Arc<Widget>>>,
size: (u16, u16),
}
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.draw_rect(width, height, self.color);
}
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.lock().unwrap().iter() {
scope.clear();
if let Some(t) = elem.get() {
scope.set_transform(&t);
}
elem.0.lock().unwrap().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);
transform.height = transform.height.max(t.y + t.height);
t.x += transform.x;
t.y += transform.y;
scope.draw();
elem.0.lock().unwrap().after_render(scope);
scope.clear();
}
scope.set_parent_size(w, h);
self.size = (transform.width, transform.height);
}
fn draw_child(&self, element: &Arc<Widget>) {
self.children.lock().unwrap().push(element.clone());
element.inject(|w| w.component(NoRender));
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
impl Div {
pub fn new(color: u32) -> Self {
Div {
color,
children: Mutex::new(Vec::new()),
size: (0, 0),
}
}
}
-141
View File
@@ -1,141 +0,0 @@
use std::sync::{Arc, Mutex};
use crate::{widget::{Element, Widget}, NoRender};
pub struct FlexRow {
color: u32,
gap: u16,
children: Mutex<Vec<Arc<Widget>>>,
size: (u16, u16),
}
pub struct FlexCol {
color: u32,
gap: u16,
children: Mutex<Vec<Arc<Widget>>>,
size: (u16, u16),
}
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.draw_rect(width, height, self.color);
}
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.lock().unwrap().iter() {
scope.clear();
if let Some(t) = elem.get() {
scope.set_transform(&t);
}
elem.0.lock().unwrap().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;
scope.draw();
elem.0.lock().unwrap().after_render(scope);
}
scope.set_parent_size(w, h);
self.size = (transform.width, transform.height);
}
fn draw_child(&self, element: &Arc<Widget>) {
self.children.lock().unwrap().push(element.clone());
element.inject(|w| w.component(NoRender));
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
impl FlexRow {
pub fn new(color: u32, gap: u16) -> Self {
Self {
children: Mutex::new(Vec::new()),
size: (0, 0),
color,
gap,
}
}
}
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.draw_rect(width, height, self.color);
}
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.lock().unwrap().iter() {
scope.clear();
if let Some(t) = elem.get() {
scope.set_transform(&t);
}
elem.0.lock().unwrap().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);
transform.height = transform.height.max(t.height);
t.x += transform.x + v;
t.y += transform.y;
v += t.width + self.gap;
scope.draw();
elem.0.lock().unwrap().after_render(scope);
}
scope.set_parent_size(w, h);
self.size = (transform.width, transform.height);
}
fn draw_child(&self, element: &Arc<Widget>) {
self.children.lock().unwrap().push(element.clone());
element.inject(|w| w.component(NoRender));
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
impl FlexCol {
pub fn new(color: u32, gap: u16) -> Self {
Self {
children: Mutex::new(Vec::new()),
size: (0, 0),
color,
gap,
}
}
}
-37
View File
@@ -1,37 +0,0 @@
pub mod div;
pub mod flex;
pub mod shape;
pub use div::*;
pub use flex::*;
pub use shape::*;
use crate::Element;
impl Element for String {
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
scope.draw_text(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(&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
}
}
-59
View File
@@ -1,59 +0,0 @@
use crate::widget::Element;
pub struct RoundedOutline;
impl Element for RoundedOutline {
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
let (w, h) = scope.get_size_or_parent();
if w > 2 && h > 2 {
let d = "─".repeat(w as usize - 2);
scope.draw_text(&format!(
"╭{d}╮{}\n╰{d}╯",
format!("\n│{}│", " ".repeat(w as usize - 2)).repeat(h as usize - 2),
));
}
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
impl RoundedOutline {
pub fn new() -> Self {
Self
}
}
pub struct Outline;
impl Element for Outline {
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
let (w, h) = scope.get_size_or_parent();
if w > 2 && h > 2 {
let d = "─".repeat(w as usize - 2);
scope.draw_text(&format!(
"┌{d}┐{}\n└{d}┘",
format!("\n│{}│", " ".repeat(w as usize - 2)).repeat(h as usize - 2),
));
}
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
impl Outline {
pub fn new() -> Self {
Self
}
}
+87
View File
@@ -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))
}
}
}
}
}
-27
View File
@@ -1,27 +0,0 @@
use std::sync::Arc;
use crate::{component, extensions::Extension, widget::Widget, Screen};
pub struct IdExtension(pub Arc<Screen>);
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
}
}
component!(Id(pub usize));
-59
View File
@@ -1,59 +0,0 @@
pub mod id;
pub mod resources;
pub mod tick;
pub mod velocity;
pub use id::*;
pub use resources::*;
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 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>())
}
}
-22
View File
@@ -1,22 +0,0 @@
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct VecResource<T>(Arc<Mutex<Box<dyn FnMut(&T) + Send + Sync>>>);
impl<T: Send + Sync + 'static> VecResource<T> {
pub fn new() -> Self {
Self(Arc::new(Mutex::new(Box::new(|_| {}))))
}
pub fn iterate<F: FnMut(&T) + Send + Sync + 'static>(&self, f: F) {
*self.0.lock().unwrap() = Box::new(f);
}
pub fn push(&self, e: T) {
let i = self.0.clone();
std::thread::spawn(move || {
(i.lock().unwrap())(&e);
});
}
}
-29
View File
@@ -1,29 +0,0 @@
use std::{fmt::Debug, sync::Arc};
use crate::extensions::Extension;
use crate::extensions::Handler;
use crate::{event, Screen};
pub struct TickExtension(pub u16);
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() {
if let Some(on_tick) = w.get::<Handler<TickEvent>>() {
on_tick.call(&w, &TickEvent(tick))
}
}
tick += 1;
std::thread::sleep(std::time::Duration::from_millis(rate_dur));
}
}
});
}
}
event!(TickEvent(pub u32));
-66
View File
@@ -1,66 +0,0 @@
use std::sync::Arc;
use crate::{
component,
extensions::Extension,
style::{Position, Transform},
widget::Widget,
Screen,
};
pub struct VelocityExtension;
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;
}
}
}
}
impl VelocityExtension {
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));
}
}
});
}
}
component!(Velocity(pub i32, pub i32));
+37 -37
View File
@@ -1,58 +1,58 @@
use std::sync::Arc; use std::sync::Arc;
use crate::{ use crate::{
state::DependencyHandler, component::{Context, Scope},
widget::{Widget, WidgetLoad}, state::HookDependency,
Screen, View,
}; };
pub enum RsxElement { pub enum RsxScope {
Element( Static(Arc<Scope>),
Box<dyn FnMut() -> WidgetLoad + Send + Sync>, Dynamic(
Vec<Box<dyn DependencyHandler>>, Arc<dyn Fn(&Arc<Scope>) + Send + Sync>,
Rsx, Vec<Box<dyn HookDependency>>,
), ),
} }
pub struct Rsx(pub Vec<RsxElement>); pub struct Rsx(Vec<RsxScope>);
impl Rsx { impl Rsx {
pub fn draw(self, screen: &Arc<Screen>) { pub fn new() -> Self {
self.draw_parent(screen, None); Self(Vec::new())
} }
pub fn draw_parent(self, screen: &Arc<Screen>, parent: Option<Arc<Widget>>) { pub fn static_scope(&mut self, scope: Arc<Scope>) {
for rsx_elem in self.0 { self.0.push(RsxScope::Static(scope));
match rsx_elem {
RsxElement::Element(f, dep, child) => {
let w = if let Some(parent) = &parent {
let w = screen.draw_box(f);
parent.0.lock().unwrap().draw_child(&w);
w
} else {
screen.draw_box(f)
};
for d in dep {
w.dependency_box(d);
}
child.draw_parent(screen, Some(w.clone()));
}
}
}
} }
pub fn create_element<F: FnMut() -> WidgetLoad + Send + Sync + 'static>( pub fn dynamic_scope<F: Fn(&Arc<Scope>) + 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 self.0
.push(RsxElement::Element(Box::new(load), dependencies, children)); .push(RsxScope::Dynamic(Arc::new(drawer), dependencies));
} }
pub fn expand(&mut self, other: &mut Rsx) { pub fn view(&self, context: Arc<Context>) -> View {
self.0.append(&mut other.0); for scope in &self.0 {
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<_>>(),
);
}
}
}
let context = context.clone();
Arc::new({
move |ctx| {
context.draw_children(ctx);
}
})
} }
} }
+12 -123
View File
@@ -1,132 +1,21 @@
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use crate::{ use crate::render::DrawContext;
extensions::{Extension, Handler},
render_scope::RenderScope,
widget::{Element, Widget, WidgetLoad},
};
pub mod elements; pub mod component;
pub mod extensions; pub mod engine;
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::{Full, Content}, Position::{Center, End}};
} }
pub struct Screen { pub type View = Arc<dyn Fn(&mut DrawContext) + Send + Sync>;
pub widgets: Mutex<Vec<Arc<Widget>>>, pub type ViewWrapper = Arc<dyn Fn(&mut DrawContext, View) + Send + Sync>;
extensions: Mutex<Vec<Arc<Mutex<Box<dyn Extension + Send + Sync>>>>>,
}
event!(RenderWrapperEvent(*mut RenderScope));
component!(NoRender);
impl RenderWrapperEvent {
pub fn get_scope(&self) -> &mut RenderScope {
unsafe { &mut *self.0 }
}
}
unsafe impl Send for RenderWrapperEvent {}
unsafe impl Sync for RenderWrapperEvent {}
impl Screen {
pub fn new() -> Arc<Self> {
Arc::new(Self {
widgets: Mutex::new(Vec::new()),
extensions: Mutex::new(Vec::new()),
})
}
pub fn draw<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(
self: &Arc<Self>,
element: F,
) -> Arc<Widget> {
let w = Arc::new(Widget::new(Box::new(element)));
self.widgets.lock().unwrap().push(w.clone());
w
}
pub fn draw_box(
self: &Arc<Self>,
element: Box<dyn FnMut() -> WidgetLoad + Send + Sync>,
) -> Arc<Widget> {
let w = Arc::new(Widget::new(Box::new(element)));
self.widgets.lock().unwrap().push(w.clone());
w
}
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))));
}
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()?;
loop {
self.render()?;
std::thread::sleep(std::time::Duration::from_millis(28));
}
}
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 let Some(NoRender) = elem.get() {
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(t) = elem.get() {
scope.set_transform(&t);
}
for ext in self.extensions.lock().unwrap().iter() {
ext.lock().unwrap().render_widget(&mut scope, elem);
}
elem.0.lock().unwrap().render(&mut scope);
if let Some(t) = elem.get() {
scope.set_transform(&t);
}
scope.draw();
elem.0.lock().unwrap().after_render(&mut scope);
}
elem.auto_refresh();
}
Ok(())
}
}
+149 -159
View File
@@ -1,175 +1,165 @@
#[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
}
}
};
}
#[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
}
}
};
}
/// Macro to create an event handler closure that calls a method on `self`
///
/// This macro automates the pattern of capturing `self` as a raw pointer,
/// then passing an event to a method on `self` inside an unsafe closure.
///
/// # Parameters
/// - `$self_ty`: The self type.
/// - `$self`: The instance variable (usually `self`) to call the method on.
/// - `$events`: The event source which has an `.on` method to register the handler.
/// - `$method`: The method name on `self` to call when an event occurs.
///
/// # Usage
/// ```rust
/// event_handler!(self, events, on_keypress);
/// ```
///
/// This expands roughly to:
/// ```rust
/// let self_ref = self as *mut Self;
/// events.on(move |event| unsafe { (*self_ref).on_keypress(event) });
/// ```
///
/// # Safety
/// This macro uses `unsafe` code because it dereferences a raw pointer inside the closure.
/// Ensure that the `self` reference lives at least as long as the closure to avoid undefined behavior.
///
/// # Why use raw pointers here?
/// Often, event handlers require `'static` closures, but `self` is a stack reference.
/// Capturing `self` directly is not possible, so this workaround uses a raw pointer.
#[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) });
}};
}
#[macro_export]
macro_rules! transform {
($($f:ident: $v:expr),* $(,)?) => {{
let mut t = Transform::new();
$(t.$f = $v.into();)*
t
}};
}
#[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
}}; }};
} }
#[macro_export] #[macro_export]
macro_rules! rsx_inner { macro_rules! rsx_scope {
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $s:literal $($rest:tt)*) => { ($rsx:expr, for $(%$($dep:ident $(as $dp:pat,)?),+)? ($p:pat in $v: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)* };
};
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $name:path { $($inner:tt)* } ($($e:expr),*) $($rest:tt)*) => { $rsx.dynamic_scope({
$r.create_element({ $(let $dep = $dep.clone();)* move || { $($($crate::rsx_dep!($dep $(as $dp)?);)+)?
$crate::widget::WidgetLoad::new(<$name>::new($($e),*)) $(.component($comp))* move |scope| {
} }, vec![$(Box::new($dep.clone())),*], $crate::rsx!{ $($inner)* }); scope.children.lock().unwrap().clear();
$crate::rsx_inner! { $r, $($rest)* }; for $p in $v {
$crate::rsx_child!(scope, $($inner)*);
}
}
}, vec![$($(Box::new($dep)),+)?]);
}
$crate::rsx_scope!($rsx, $($rest)*);
};
($rsx:expr, if $(%$($dep:ident $(as $dp:pat,)?),+)? ($st:expr) {$($inner:tt)*} $($rest:tt)*) => {
{
$($($crate::rsx_dep!($dep);)+)?
$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)*);
};
($rsx:expr, $(%$($dep:ident $(as $dp:pat,)?),+)? $text:literal @$d:expr; $($rest:tt)*) => {
{
let scope = $crate::component::Scope::new();
$($($crate::rsx_dep!($dep $(as $dp)?);)+)?
$crate::rsx_child!(scope, $text @$d;);
$rsx.static_scope(scope);
}
$crate::rsx_scope!($rsx, $($rest)*);
};
($rsx:expr, $(%$($dep:ident $(as $dp:pat,)?),+)? $text:literal $($rest:tt)*) => {
{
let scope = $crate::component::Scope::new();
$($($crate::rsx_dep!($dep $(as $dp)?);)+)?
$crate::rsx_child!(scope, $text);
$rsx.static_scope(scope);
}
$crate::rsx_scope!($rsx, $($rest)*);
};
($rsx:expr, $component:ident ($ctx:ident, $view:ident) $body:block $($rest:tt)*) => {
{
let scope = $crate::component::Scope::new();
$crate::rsx_child!(scope, $component ($ctx, $view) $body);
$rsx.static_scope(scope);
}
$crate::rsx_scope!($rsx, $($rest)*);
}; };
($rsx:expr, $component:ident $($rest:tt)*) => {
{
let scope = $crate::component::Scope::new();
$crate::rsx_child!(scope, $component);
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $name:path { $($inner:tt)* } $($rest:tt)*) => { $rsx.static_scope(scope);
$r.create_element({ $(let $dep = $dep.clone();)* move || { }
$crate::widget::WidgetLoad::new(<$name>::new()) $(.component($comp))*
} }, vec![$(Box::new($dep.clone())),*], $crate::rsx!{ $($inner)* }); $crate::rsx_scope!($rsx, $($rest)*);
$crate::rsx_inner! { $r, $($rest)* };
}; };
($rsx:expr, !mount $mount:ident $($rest:tt)*) => {
{
$mount.mount();
}
($r:expr, $expand:ident => ($($inner:tt)*) $($rest:tt)*) => { $crate::rsx_scope!($rsx, $($rest)*);
$r.expand(&mut $expand($($inner)*));
$crate::rsx_inner! { $r, $($rest)* };
}; };
($rsx:expr,) => {};
}
($r: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();
};
} }
-28
View File
@@ -1,28 +0,0 @@
use osui::prelude::*;
fn main() -> std::io::Result<()> {
let screen = Screen::new();
app().draw(&screen);
screen.run()
}
fn app() -> Rsx {
rsx! {
@transform! {
width: Full,
height: Full,
};
Div {
@transform! {
width: Full,
height: Full,
};
RoundedOutline {}
@Transform::center();
"Welcome To OSUI!"
} (0x000000)
}
}
+77
View File
@@ -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));
}
}
-154
View File
@@ -1,154 +0,0 @@
use std::fmt::Debug;
use crate::{
style::{RawTransform, Transform},
utils::{self, hex_ansi_bg},
};
#[derive(Clone)]
enum RenderMethod {
Text(String),
TextColored(String, u32),
Rectangle(u16, u16, u32),
}
#[derive(Clone)]
pub struct RenderScope {
transform: RawTransform,
render_stack: Vec<RenderMethod>,
parent_width: u16,
parent_height: u16,
}
impl RenderScope {
pub fn new() -> RenderScope {
RenderScope {
transform: RawTransform::new(),
render_stack: Vec::new(),
parent_width: 0,
parent_height: 0,
}
}
pub fn set_transform_raw(&mut self, transform: RawTransform) {
self.transform = transform;
}
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);
}
pub fn draw_text(&mut self, text: &str) {
self.render_stack.push(RenderMethod::Text(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);
}
pub fn draw_text_colored(&mut self, text: &str, color: u32) {
self.render_stack
.push(RenderMethod::TextColored(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);
}
pub fn draw_rect(&mut self, width: u16, height: u16, color: u32) {
self.render_stack
.push(RenderMethod::Rectangle(width, height, color));
self.transform.width = self.transform.width.max(width);
self.transform.height = self.transform.height.max(height);
}
pub fn draw(&self) {
for m in &self.render_stack {
match m {
RenderMethod::Text(t) => {
utils::print(self.transform.x, self.transform.y, t);
}
RenderMethod::TextColored(t, c) => utils::print(
self.transform.x,
self.transform.y,
&(utils::hex_ansi(*c) + t),
),
RenderMethod::Rectangle(width, height, color) => {
utils::print_liner(
self.transform.x,
self.transform.y,
&hex_ansi_bg(*color),
&std::iter::repeat(" ".repeat(*width as usize))
.take(*height as usize)
.collect::<Vec<_>>()
.join("\n"),
);
}
}
}
}
pub fn clear(&mut self) {
self.render_stack.clear();
self.transform.width = 0;
self.transform.height = 0;
self.transform.x = 0;
self.transform.y = 0;
}
pub fn get_size(&self) -> (u16, u16) {
(self.transform.width, self.transform.height)
}
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
},
)
}
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
},
)
}
pub fn get_parent_size(&self) -> (u16, u16) {
(self.parent_width, self.parent_height)
}
pub fn set_parent_size(&mut self, width: u16, height: u16) {
self.parent_width = width;
self.parent_height = height;
}
pub fn get_transform_mut(&mut self) -> &mut RawTransform {
&mut self.transform
}
pub fn get_transform(&self) -> &RawTransform {
&self.transform
}
}
impl Debug for RenderScope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "RenderScope")
}
}
+159 -43
View File
@@ -1,97 +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},
}; };
#[derive(Debug, Clone)] use crate::prelude::Context;
pub struct State<T> {
inner: Arc<Mutex<Inner<T>>>, #[derive(Clone)]
} pub struct HookEffect(Arc<Mutex<dyn FnMut() + Send + Sync>>);
#[derive(Debug)] #[derive(Debug)]
pub struct Inner<T> { pub struct State<T> {
value: T, value: Arc<Mutex<T>>,
dependencies: usize, dependents: Arc<Mutex<Vec<HookEffect>>>,
changed: usize,
} }
pub struct Inner<'a, T> {
value: MutexGuard<'a, T>,
dependents: Arc<Mutex<Vec<HookEffect>>>,
updated: bool,
}
#[derive(Debug, Clone)]
pub struct Mount(Arc<Mutex<bool>>, Arc<Mutex<Vec<HookEffect>>>);
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> { pub fn clone(&self) -> Self {
fn check(&self) -> bool { Self {
let mut inner = self.inner.lock().unwrap(); dependents: self.dependents.clone(),
let i = inner.changed > 0; value: self.value.clone(),
if i {
inner.changed -= 1;
} }
i
}
fn add(&self) {
let mut inner = self.inner.lock().unwrap();
inner.dependencies += 1;
} }
} }
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 {
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; 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 DependencyHandler: std::fmt::Debug + Send + Sync { pub trait HookDependency {
fn add(&self); fn on_update(&self, hook: HookEffect);
fn check(&self) -> bool; }
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,
);
} }
-153
View File
@@ -1,153 +0,0 @@
use crate::component;
#[derive(Debug, Clone)]
pub struct RawTransform {
pub x: u16,
pub y: u16,
pub width: u16,
pub height: u16,
}
#[derive(Debug, Clone)]
pub enum Position {
Const(u16),
Center,
End,
}
#[derive(Debug, Clone)]
pub enum Dimension {
Full,
Content,
Const(u16),
}
component!(Transform {
pub x: Position,
pub y: Position,
pub mx: i32,
pub my: i32,
pub width: Dimension,
pub height: Dimension,
});
impl Transform {
pub fn new() -> Transform {
Transform {
x: Position::Const(0),
y: Position::Const(0),
mx: 0,
my: 0,
width: Dimension::Content,
height: Dimension::Content,
}
}
pub fn center() -> Transform {
Transform {
x: Position::Center,
y: Position::Center,
mx: 0,
my: 0,
width: Dimension::Content,
height: Dimension::Content,
}
}
pub fn bottom(mut self) -> Self {
self.y = Position::End;
self
}
pub fn right(mut self) -> Self {
self.x = Position::End;
self
}
pub fn margin(mut self, x: i32, y: i32) -> Self {
self.mx = x;
self.my = y;
self
}
pub fn dimensions(mut self, width: u16, height: u16) -> Self {
self.width = Dimension::Const(width);
self.height = Dimension::Const(height);
self
}
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);
}
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 {
pub fn new() -> RawTransform {
RawTransform {
x: 0,
y: 0,
width: 0,
height: 0,
}
}
}
impl Dimension {
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 {
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
View File
@@ -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();
}
}
-140
View File
@@ -1,140 +0,0 @@
use std::{
any::{Any, TypeId},
collections::HashMap,
sync::{Arc, Mutex},
};
use crate::{render_scope::RenderScope, state::DependencyHandler};
pub type BoxedElement = Box<dyn Element + Send + Sync>;
pub type BoxedComponent = Box<dyn Component + Send + Sync>;
pub trait Element: Send + Sync {
#[allow(unused)]
fn render(&mut self, scope: &mut RenderScope) {}
#[allow(unused)]
fn after_render(&mut self, scope: &mut RenderScope) {}
#[allow(unused)]
fn draw_child(&self, element: &Arc<Widget>) {}
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
pub trait Component: Send + Sync {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
pub struct Widget(
pub 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>>>,
);
impl Widget {
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),
)
}
pub fn inject<F: FnMut(WidgetLoad) -> WidgetLoad + 'static + Send + Sync>(
self: &Arc<Self>,
f: F,
) {
{
*self.4.lock().unwrap() = Some(Box::new(f));
}
self.refresh();
}
pub fn refresh(self: &Arc<Self>) {
let w = (self.2.lock().unwrap())();
match &mut *self.4.lock().unwrap() {
Some(inject) => {
let w = inject(w);
*self.0.lock().unwrap() = w.0;
*self.1.lock().unwrap() = w.1;
}
None => {
*self.0.lock().unwrap() = w.0;
*self.1.lock().unwrap() = w.1;
}
}
}
pub fn auto_refresh(self: &Arc<Self>) {
for d in self.3.lock().unwrap().iter() {
if d.check() {
self.refresh();
}
}
}
pub fn dependency<D: DependencyHandler + 'static>(self: &Arc<Self>, d: D) -> &Arc<Self> {
d.add();
self.3.lock().unwrap().push(Box::new(d));
self
}
pub fn dependency_box(self: &Arc<Self>, d: Box<dyn DependencyHandler>) -> &Arc<Self> {
d.add();
self.3.lock().unwrap().push(d);
self
}
pub fn component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
self.1
.lock()
.unwrap()
.entry(c.type_id())
.or_insert_with(|| Box::new(c));
self
}
pub fn set_component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
self.1.lock().unwrap().insert(c.type_id(), Box::new(c));
self
}
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(|c| c.clone())
}
}
pub struct WidgetLoad(BoxedElement, HashMap<TypeId, BoxedComponent>);
impl WidgetLoad {
pub fn new<E: Element + 'static>(e: E) -> Self {
Self(Box::new(e), HashMap::new())
}
pub fn component<C: Component + 'static>(mut self, c: C) -> Self {
self.1.entry(c.type_id()).or_insert_with(|| Box::new(c));
self
}
pub fn set_component<C: Component + 'static>(mut self, c: C) -> Self {
self.1.insert(c.type_id(), Box::new(c));
self
}
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())
}
}