121 Commits
Author SHA1 Message Date
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
selimaj-dev 5d1361621d version .9alpha2 2025-07-29 20:55:06 +02:00
selimaj-dev 5ca7221afa outlines 2025-07-29 20:54:12 +02:00
selimaj-dev 71660418a1 prelude and transform macro 2025-07-29 19:42:56 +02:00
selimaj-dev 26eb1679f6 size full and content 2025-07-29 18:16:37 +02:00
selimaj-dev db66803347 state management as a child 2025-07-29 17:51:03 +02:00
selimaj-dev de9039dbaf refactored flex 2025-07-29 17:44:10 +02:00
selimaj-dev e2d7c1ef91 refactored div 2025-07-29 17:08:25 +02:00
selimaj-dev 3a7d69cb04 removed styling 2025-07-29 16:25:52 +02:00
selimaj-dev a75c02fa90 fixed nested issue 2025-07-29 01:51:07 +02:00
selimaj-dev 250dde8f9e rename grid to flex 2025-07-28 19:44:16 +02:00
selimaj-dev e3bbda6b59 expandable rsx 2025-07-28 19:43:58 +02:00
selimaj-dev b0b1835cc1 div example 2025-07-28 19:27:15 +02:00
selimaj-dev a59a8eeb73 Widget injection 2025-07-28 19:24:50 +02:00
selimaj-dev a8e832892b rsx child 2025-07-28 18:47:59 +02:00
selimaj-dev 26c112bdb2 rsx component 2025-07-28 15:32:11 +02:00
selimaj-dev a79617e219 changed main code 2025-07-28 15:28:44 +02:00
selimaj-dev 10fae90ecc small fix with rsx 2025-07-28 15:23:12 +02:00
selimaj-dev 5c2c5ba46b Improved frontend 2025-07-28 15:22:17 +02:00
selimaj-dev 211b5aa95c Moved state 2025-07-28 15:02:35 +02:00
selimaj-dev 02bdca151b Dynamic Widget system 2025-07-28 15:02:22 +02:00
selimaj-dev 00f7493741 Rsx 2025-07-28 00:03:51 +02:00
selimaj-dev d9c23f1f09 Rsx 2025-07-28 00:01:12 +02:00
selimaj-dev cba301db74 State management 2025-07-27 19:53:45 +02:00
selimaj-dev 327f14d9ed semi working state management 2025-07-27 02:35:36 +02:00
selimaj-dev 0878cad01c Simple state management 2025-07-26 00:26:30 +02:00
selimaj-dev 3d995671cd resource management 2025-07-07 10:05:23 -05:00
selimaj-dev 5fabd1a8ab resources (not fully working yet) 2025-07-06 02:12:10 -05:00
selimaj-dev 4dfbee5984 position fix 2025-07-05 10:06:48 -05:00
selimaj-dev 2f328f6762 working grid dimensions 2025-07-05 09:13:05 -05:00
selimaj-dev 8ae6fb49db fully working h and v grid 2025-07-05 05:21:16 -05:00
selimaj-dev 6255b9c4f4 vgrid 2025-07-05 04:59:40 -05:00
selimaj-dev ec963707a1 working divs 2025-07-05 04:40:05 -05:00
selimaj-dev cec25c02d5 better handlers 2025-07-05 06:48:21 +02:00
selimaj-dev 661756eccd handlers and ids 2025-07-05 06:28:50 +02:00
selimaj-dev 921bfa27c1 improved velocity algorithm 2025-06-30 08:31:28 -05:00
selimaj-dev bbaa9d09e1 multithreading 2025-06-29 22:56:53 +02:00
selimaj-dev 85bfa0f45f working extension system 2025-06-29 11:49:11 -05:00
selimaj-dev af719d83db redesign 2025-06-29 11:20:36 -05:00
selimaj-dev cff2e315ca alpha 1 2025-06-29 01:51:57 +02:00
selimaj-dev eb64a77aac state fix 2025-06-28 16:00:16 -05:00
selimaj-dev bb0ef3adc4 improved state management 2025-06-28 11:30:09 -05:00
selimaj-dev fd73514a7b recoursive event lock fix 2025-06-28 08:13:12 -05:00
selimaj-dev f43be496c1 better structure 2025-06-28 15:02:45 +02:00
selimaj-dev f401d4a995 better structure 2025-06-28 03:51:13 +02:00
selimaj-dev 551a062021 better state management 2025-06-28 01:57:36 +02:00
selimaj-dev 627ab80338 state management 2025-06-27 15:51:22 -05:00
selimaj-dev 3adfff41fb testing state management 2025-06-27 15:32:55 -05:00
selimaj-dev 6c8ff5f3da margin 2025-06-27 15:06:45 -05:00
selimaj-dev 9715630d9f few changes 2025-06-27 15:02:13 -05:00
selimaj-dev 3cacd42421 event handler on events 2025-06-27 12:22:59 -05:00
selimaj-dev 15b61d57c8 slightly improved structure and added a few more elements 2025-06-27 12:10:25 -05:00
selimaj-dev dfb17ab48e working center 2025-06-26 02:42:27 -05:00
selimaj-dev 82b847314e transform and components 2025-06-26 09:24:35 +02:00
selimaj-dev f363bbdae1 slight re-structure 2025-06-26 07:13:41 +02:00
selimaj-dev 8274afff04 finally working event system 2025-06-25 14:25:26 -05:00
selimaj-dev 7693711aa9 test 2025-06-25 17:18:23 +02:00
selimaj-dev 08f1d3364b testing for event handling 2025-06-24 15:25:25 -05:00
selimaj-dev 6c0dde8e85 test 2025-06-24 17:21:12 +02:00
selimaj-dev f72959bcee test 2025-06-24 03:16:24 +02:00
selimaj-dev 52f4dcfb2f mouse events 2025-01-21 21:06:10 +01:00
selimaj-dev 09d1ee21bf done 2025-01-21 12:14:02 +01:00
selimaj-dev aa55cc059a documented the code 2025-01-20 00:51:03 +01:00
selimaj-dev fda5387ccc few changes 2025-01-19 23:24:55 +01:00
selimaj-dev 5a21f9f740 some small changes 2025-01-19 13:14:30 +01:00
selimaj-dev 49ce197f78 if tree 2025-01-18 23:55:46 +01:00
selimaj-dev fb82c611df small changes 2025-01-18 23:39:21 +01:00
selimaj-dev ab5554abce expanded components 2025-01-18 18:13:45 +01:00
selimaj-dev 9ecf8de501 added positioning in rsx 2025-01-18 15:04:09 +01:00
selimaj-dev bde4438663 few changes 2025-01-17 22:13:42 +01:00
selimaj-dev a2ec2f9d41 few changes 2025-01-17 13:18:39 +01:00
selimaj-dev e2e1a466f4 state management 2025-01-17 02:28:54 +01:00
selimaj-dev 85dd5a6f66 few changes 2025-01-17 01:01:27 +01:00
selimaj-dev a6472f8e2e few changes 2025-01-17 01:01:14 +01:00
selimaj-dev eeefd1f002 rewrite 2025-01-16 23:47:34 +01:00
selimaj-dev 6878777140 rewrite 2025-01-15 09:25:58 -06:00
30 changed files with 2513 additions and 1773 deletions
+5
View File
@@ -0,0 +1,5 @@
debug
target
github
Cargo.lock
.DS_Store
+6 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "osui"
version = "0.0.8-alpha.2"
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"
description = "A TUI library for advanced uis"
@@ -8,6 +8,10 @@ repository = "https://github.com/osui-rs/osui"
homepage = "https://osui.netlify.app"
documentation = "https://osui.netlify.app/docs/"
[features]
no_rsx = []
no_elem = []
[lib]
name = "osui"
path = "src/lib.rs"
@@ -21,8 +25,7 @@ cc = "1.0"
[dependencies]
crossterm = "0.28.1"
dyn-clone = "1.0.17"
osui-element = "0.1.23"
figlet-rs = "0.1.5"
[profile.dev]
opt-level = 1
+15
View File
@@ -20,6 +20,21 @@
<b>OSUI is a customizable terminal user interface (TUI) library written in Rust. It provides a set of components and rsx to build interactive command-line interfaces with ease.</b>
</p>
```rust
use osui::prelude::*;
fn main() -> std::io::Result<()> {
let screen = Screen::new();
rsx! {
"Hello, World"
}
.draw(&screen);
screen.run()
}
```
## [Documentation](https://osui.netlify.app/docs)
## Features
-206
View File
@@ -1,206 +0,0 @@
#[macro_export]
macro_rules! __css {
($_style:expr,)=>{};
// percentage (n%)
(
$_style:expr, $name:ident: $value:literal% $(, $($rest:tt)*)?
) => {{
$_style.$name = (true, Number::Pe($value));
$crate::__css!($_style, $($($rest)*)?);
}};
// Number
(
$_style:expr, $name:ident: $value:literal px $(, $($rest:tt)*)?
) => {{
$_style.$name = (true, Number::Px($value));
$crate::__css!($_style, $($($rest)*)?);
}};
// Vector
(
$_style:expr, $name:ident: [$($inner:tt),*] $(, $($rest:tt)*)?
) => {{
$_style.$name = (true, vec![$($inner),*]);
$crate::__css!($_style, $($($rest)*)?);
}};
// Normal
(
$_style:expr, $name:ident: $value:expr $(, $($rest:tt)*)?
) => {{
$_style.$name = (true, $value);
$crate::__css!($_style, $($($rest)*)?);
}};
}
#[macro_export]
macro_rules! _css {
($_style:expr,) => {};
(
$hm:expr, $($($name:ident)-+),* { $($inner:tt)* } $($rest:tt)*
) => {{
let mut _style = $crate::ui::StyleElement::default();
$crate::__css!(_style, $($inner)*);
$(
$hm.insert(
$crate::ui::StyleName::Class(String::from(stringify!($($name)-+).replace(' ', ""))),
_style.clone(),
);
)*
$crate::_css!($hm, $($rest)*);
}};
(
$hm:expr, $($($name:ident)-+),*: $state:literal { $($inner:tt)* } $($rest:tt)*
) => {{
let mut _style = $crate::ui::StyleElement::default();
$crate::__css!(_style, $($inner)*);
$(
$hm.insert(
$crate::ui::StyleName::ClassState(String::from(stringify!($($name)-+).replace(' ', "")), String::from($state)),
_style.clone(),
);
)*
$crate::_css!($hm, $($rest)*);
}};
(
$hm:expr, $($name:literal),+ { $($inner:tt)* } $($rest:tt)*
) => {{
let mut _style = $crate::ui::StyleElement::default();
$crate::__css!(_style, $($inner)*);
$(
$hm.insert(
$crate::ui::StyleName::Class(String::from($name)),
_style,
);
)+
$crate::_css!($hm, $($rest)*);
}};
(
$hm:expr, $($name:literal),+: $state:literal { $($inner:tt)* } $($rest:tt)*
) => {{
let mut _style = $crate::ui::StyleElement::default();
$crate::__css!(_style, $($inner)*);
$(
$hm.insert(
$crate::ui::StyleName::ClassState(String::from($name), String::from($state)),
_style,
);
)+
$crate::_css!($hm, $($rest)*);
}};
}
/// Creates a styling map `Css`
///
/// # Example
/// ```
/// css! {
/// "btn" {
/// color: Red,
/// }
/// "btn": "clicked" {
/// color: Blue,
/// }
/// }
/// ```
///
/// # Returns
/// `Css`
#[macro_export]
macro_rules! css {
(
$($inner:tt)*
) => {{
#[allow(unused_mut)]
let mut hm: $crate::ui::Css = std::collections::HashMap::new();
$crate::_css!(hm, $($inner)*);
hm
}};
}
#[macro_export]
macro_rules! style {
(
$key:ident: $value:literal% $(, $($rest:tt)*)?
) => {{
let mut _style = $crate::ui::Style::default();
$crate::__css!(_style.0, $key: $crate::ui::Number::Pe($value));
$crate::style!{ _style; $($($rest)*)? }
}};
(
$key:ident: $value:literal px $(, $($rest:tt)*)?
) => {{
let mut _style = $crate::ui::Style::default();
$crate::__css!(_style.0, $key: $crate::ui::Number::Px($value));
$crate::style!{ _style; $($($rest)*)? }
}};
(
$style:expr; $key:ident: $value:literal% $(, $($rest:tt)*)?
) => {{
$crate::__css!($style.0, $key: $crate::ui::Number::Pe($value));
$crate::style!{ $style; $($($rest)*)? }
}};
(
$style:expr; $key:ident: $value:literal px $(, $($rest:tt)*)?
) => {{
$crate::__css!($style.0, $key: $crate::ui::Number::Px($value));
$crate::style!{ $style; $($($rest)*)? }
}};
(
$key:ident: $value:expr $(, $($rest:tt)*)?
) => {{
let mut _style = $crate::ui::Style::default();
$crate::__css!(_style.0, $key: $value);
$crate::style!{ _style; $($($rest)*)? }
}};
(
$style:expr; $key:ident: $value:expr $(, $($rest:tt)*)?
) => {{
let mut style_elem = $crate::ui::StyleElement::default();
$crate::__css!($style.0, $key: $value);
$crate::style!{ $style; $($($rest)*)? }
}};
(
($key:ident): $value:expr $(, $($rest:tt)*)?
) => {{
let mut _style = $crate::ui::Style::default();
$crate::__css!(_style.0, ($key): $value);
$crate::style!{ _style; $($($rest)*)? }
}};
(
$style:expr; $key:literal: $value:expr $(, $($rest:tt)*)?
) => {{
let mut style_elem = $crate::ui::StyleElement::default();
$crate::__css!($style.0, $key: $value);
$crate::style!{ $style; $($($rest)*)? }
}};
(
$kind:ident {$($inner:tt)*} $(, $($rest:tt)*)?
) => {{
let mut _style = $crate::ui::Style::default();
let mut style_elem = $crate::ui::StyleElement::default();
$crate::__css!(style_elem, $($inner)*);
_style.1.insert(stringify!($kind).to_string(), style_elem);
$crate::style!{ _style; $($($rest)*)? }
}};
(
$style:expr; $kind:ident {$($inner:tt)*} $(, $($rest:tt)*)?
) => {{
let mut style_elem = $crate::ui::StyleElement::default();
$crate::__css!(style_elem, $($inner)*);
$style.1.insert(stringify!($kind).to_string(), style_elem);
$crate::style!{ $style; $($($rest)*)? }
}};
(
$style:expr;
) => {{
$style
}};
() => {{
$crate::ui::Style::default()
}};
}
+62
View File
@@ -0,0 +1,62 @@
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 { }
}
}
}
}
+75
View File
@@ -0,0 +1,75 @@
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
}
}
+158
View File
@@ -0,0 +1,158 @@
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
}
}
+63
View File
@@ -0,0 +1,63 @@
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
}
}
+80
View File
@@ -0,0 +1,80 @@
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,
}
}
}
+41
View File
@@ -0,0 +1,41 @@
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
}
}
+102
View File
@@ -0,0 +1,102 @@
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
}
}
-132
View File
@@ -1,132 +0,0 @@
pub mod counter_example {
use crate::prelude::*;
#[component]
pub fn App() -> Element {
let count = use_state(0);
rsx! {
@SetStyle(styling())
button {
class: "btn",
on_click: fn(_, _, _) @count {
count += 1;
},
"The current count is: {count}"
}
}
}
pub fn styling() -> Css {
css! {
btn {
outline: true,
outline_color: Red
}
}
}
}
pub mod todo_example {
use crate::prelude::*;
#[component]
pub fn App() -> Element {
let todo = vec!["Todo", "Hovering", "Completed", "Foo", "Bar"];
rsx! {
@SetStyle(styling())
@SetChild(2)
text { class: "title", static "Todo list app made with OSUI" }
text { class: "title", "{}", "-".repeat(crossterm::terminal::size().unwrap().0 as usize) }
for (t in todo) {
ersx!(button { class: "todo", on_click: fn(btn: &mut Button, _, _) {
btn.class = if btn.class == "todo" {
"complete"
} else {
"todo"
};
}, "{t}" } )
}
}
}
pub fn styling() -> Css {
css! {
todo {
x: 0 px,
y: Auto,
color: Red,
}
todo: "hover" {
color: Blue,
}
complete {
x: 0 px,
y: Auto,
color: Green,
}
complete: "hover" {
color: Cyan
}
title {
x: 0 px,
y: Auto,
}
title: "hover" {
color: Blue
}
}
}
}
pub mod login_example {
use crate::prelude::*;
#[component]
pub fn App() -> Element {
rsx! {
@SetStyle(styling())
input { class: "input", id: "usr", on_click: fn(_, _, document) {
let root = document.get_root::<Div>();
root.children.set_index(1);
}, "username: " }
input { class: "input", id: "psw", on_click: fn(_, _, document) {
let root = document.get_root::<Div>();
root.children.set_index(2);
}, "password: " }
button { class: "input", on_click: fn(_, _, document) {
if let Some(usr) = document.get_element_by_id::<Input>("usr") {
if let Some(psw) = document.get_element_by_id::<Input>("psw") {
document.draw(rsx! {
text { static "Username: {}\nPassword: {}", usr.text, psw.text }
});
}
}
}, "Submit" }
}
}
pub fn styling() -> Css {
css! {
input {
width: 50 px,
outline: true,
y: Auto,
x: 0 px,
caret: String::new(),
}
input: "hover" {
outline_color: Red,
caret: String::from("█"),
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
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
}
}
+26
View File
@@ -0,0 +1,26 @@
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
}
}
+66
View File
@@ -0,0 +1,66 @@
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()
}
}
+26
View File
@@ -0,0 +1,26 @@
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));
}
}
});
}
}
+64
View File
@@ -0,0 +1,64 @@
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));
}
}
});
}
}
+103
View File
@@ -0,0 +1,103 @@
//! 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 crate::{
state::DependencyHandler,
widget::{StaticWidget, Widget, WidgetLoad},
Screen,
};
/// Represents a single element in the RSX tree.
pub enum RsxElement {
/// A static widget with children.
Element(StaticWidget, Rsx),
/// 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.
/// This is typically created via the `rsx!` macro and rendered using a `Screen`.
pub struct Rsx(pub Vec<RsxElement>);
impl Rsx {
/// Draws the RSX tree onto the given screen without a parent widget.
///
/// 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.
///
/// 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 {
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,
load: F,
dependencies: Vec<Box<dyn DependencyHandler>>,
children: Rsx,
) {
self.0.push(RsxElement::DynElement(
Box::new(load),
dependencies,
children,
));
}
/// Adds a statically defined element to the RSX tree with its children.
pub fn create_element_static(&mut self, element: StaticWidget, children: Rsx) {
self.0.push(RsxElement::Element(element, children));
}
/// Appends the elements from another `Rsx` tree into this one.
pub fn expand(&mut self, other: &mut Rsx) {
self.0.append(&mut other.0);
}
}
+178 -486
View File
@@ -1,543 +1,235 @@
//! # OSUI
//! **OSUI** – A Rust Terminal User Interface Library
//!
//! A terminal user interface (TUI) library providing customizable components
//! to build command-line interfaces in Rust. OSUI enables users to create
//! interactive CLI applications with various UI elements and handle keyboard
//! input for real-time events.
//! 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.
//!
//! ## Example Usage
//! ✅ **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::*;
//!
//! #[component]
//! pub fn App() -> Element {
//! let count = State::new(0);
//!
//! fn main() -> std::io::Result<()> {
//! let screen = Screen::new();
//! rsx! {
//! button {
//! class: "btn",
//!
//! on_click: fn(_, _, _) @count {
//! count += 1;
//! },
//!
//! "The current count is: {count}"
//! }
//! }
//! }
//! fn main() {
//! launch!(App);
//! "👋 Hello, World!"
//! }.draw(&screen);
//! screen.run()
//! }
//! ```
//!
//! ## Modules
//! - `ui` - Contains all user interface components, enabling rich CLI experiences.
//! - `utils` - Utility functions for common TUI tasks such as clearing the screen.
//! ---
//! 🧰 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::{
collections::HashMap,
fmt::Debug,
ops::{AddAssign, SubAssign},
sync::{Arc, Mutex},
use std::sync::{Arc, Mutex};
use crate::{
extensions::{Extension, Handler},
render_scope::RenderScope,
widget::{BoxedElement, DynWidget, Element, StaticWidget, Widget, WidgetLoad},
};
use crossterm::event::Event;
use ui::{Style, StyleCore};
use utils::VisibleLength;
pub mod css;
pub mod examples;
pub mod elements;
pub mod extensions;
pub mod frontend;
pub mod macros;
pub mod rsx;
pub mod ui;
pub mod render_scope;
pub mod state;
pub mod style;
pub mod utils;
pub mod widget;
pub mod prelude {
pub use crate::ui::Color::*;
pub use crate::ui::Font::*;
pub use crate::ui::Number::{Auto, Center};
pub use crate::Instruction::*;
pub use crate::{self as osui, css, ersx, launch, rsx, ui::*, Handler};
pub use crate::{style, Component, Document};
pub use crate::{Children, Element, ElementCore, ElementWidget};
pub use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind};
pub use osui_element::component;
pub fn sleep(ms: u64) {
std::thread::sleep(std::time::Duration::from_millis(ms));
}
pub fn use_state<'a, T>(v: T) -> crate::State<T> {
crate::State::new(v)
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Type aliases
//////////////////////////////////////////////////////////////////////////////////////////////////
pub type Element = Box<dyn ElementWidget>;
//////////////////////////////////////////////////////////////////////////////////////////////////
/// Traits
//////////////////////////////////////////////////////////////////////////////////////////////////
pub trait ElementCore {
fn get_element_by_id(&mut self, id: &str) -> Option<&mut Element>;
fn get_id(&self) -> String;
fn get_class(&self) -> String;
fn get_style(&self) -> &Style;
}
pub trait ElementWidget: ElementCore + std::fmt::Debug {
fn render(&self, writer: &mut Writer);
fn event(&mut self, event: crossterm::event::Event, document: &mut Document) {
_ = (event, document)
}
fn initialize(&mut self, document: &mut Document) {
_ = document
}
}
pub trait Component: std::fmt::Debug {
type Element;
fn create_element(self) -> Self::Element;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
/// Structs
//////////////////////////////////////////////////////////////////////////////////////////////////
pub struct Handler<T>(pub Arc<Mutex<dyn FnMut(&mut T, crossterm::event::Event, &mut Document)>>);
pub struct Document {
element: *mut Element,
running: Option<bool>,
pub css: ui::Css,
}
#[derive(Debug)]
pub struct Writer {
css: *const ui::Css,
style: ui::StyleElement,
focused: bool,
size: (u16, u16),
pos: (u16, u16),
written: (u16, u16),
parent: Option<*mut Writer>,
}
pub struct State<T>(Arc<Mutex<T>>);
//////////////////////////////////////////////////////////////////////////////////////////////////
/// Enums
//////////////////////////////////////////////////////////////////////////////////////////////////
pub enum Children {
None,
Text(Arc<dyn Fn() -> String>),
StaticText(String),
Children(Vec<Element>, usize),
}
//////////////////////////////////////////////////////////////////////////////////////////////////
/// Implementations
//////////////////////////////////////////////////////////////////////////////////////////////////
impl Document {
pub fn with_elem(element: &mut Element) -> Document {
Document {
element,
running: None,
css: HashMap::new(),
}
}
pub fn exit(&mut self) {
self.running = Some(false);
}
pub fn restart(&mut self) {
self.running = Some(true);
}
pub fn get_root<T>(&self) -> &mut Box<T> {
unsafe { &mut *(self.element as *mut Element as *mut Box<T>) }
}
pub fn get_element_by_id<T>(&self, id: &str) -> Option<&mut Box<T>> {
if let Some(e) = self.get_element_by_id_raw(id) {
Some(unsafe { &mut *(e as *mut Element as *mut Box<T>) })
} else {
None
}
}
pub fn get_element_by_id_raw(&self, id: &str) -> Option<&mut Element> {
if !self.element.is_null() {
unsafe {
if (*self.element).get_id() == id {
Some(&mut *self.element)
} else {
(*self.element).get_element_by_id(id)
}
}
} else {
None
}
}
pub fn render(&self) {
if !self.element.is_null() {
let (width, height) = crossterm::terminal::size().unwrap();
let mut writer = Writer {
css: &self.css,
focused: true,
style: ui::StyleElement {
// outline: (true, true),
..Default::default()
},
size: (width, height),
pos: (1, 1),
written: (0, 0),
parent: None,
pub use crate::{
elements::*, extensions::*, frontend::*, render_scope::*, state::*, style::*, utils::*,
widget::*, *,
};
let mut frame = writer.new_frame();
utils::clear();
frame.render(true, unsafe { &*self.element });
writer.after_render(width, height);
utils::flush();
}
}
pub fn set_css(&mut self, css: ui::Css) {
self.css = css;
}
pub fn clear_css(&mut self) {
self.css.clear();
}
pub fn draw(&mut self, element: Element) {
unsafe {
*self.element = element;
(*self.element).initialize(self);
}
}
pub fn run(&mut self) -> bool {
// Set up the screen
utils::hide_cursor();
crossterm::terminal::enable_raw_mode().unwrap();
utils::clear();
self.running = None;
let element = unsafe { &mut *self.element };
self.render();
element.initialize(self);
// Send initial event
element.event(crossterm::event::Event::FocusGained, self);
while self.running == None {
self.render();
element.event(crossterm::event::read().unwrap(), self);
pub use crate::style::{
Dimension::{Content, Full},
Position::{Center, End},
};
}
utils::show_cursor();
crossterm::terminal::disable_raw_mode().unwrap();
utils::clear();
/// The main screen abstraction for rendering and managing widgets and extensions.
///
/// `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>,
}
self.running.unwrap()
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 }
}
}
impl Default for Children {
fn default() -> Self {
Self::None
}
}
unsafe impl Send for RenderWrapperEvent {}
unsafe impl Sync for RenderWrapperEvent {}
impl std::fmt::Debug for Children {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&match self {
Self::None => String::new(),
Self::Children(a, b) => format!("({b}, {a:?})"),
Self::Text(a) => format!("{:?}", a()),
Self::StaticText(a) => format!("static({a:?})"),
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
}
impl Children {
pub fn is_none(&self) -> bool {
match self {
Children::None => true,
_ => false,
}
/// 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
}
pub fn get_text(&self) -> String {
match self {
Children::Text(text) => text(),
Children::StaticText(text) => text.clone(),
_ => String::new(),
}
/// Adds an existing widget to the screen.
pub fn draw_widget(self: &Arc<Self>, widget: Arc<Widget>) {
self.widgets.lock().unwrap().push(widget);
}
pub fn set_text(&mut self, text: Arc<dyn Fn() -> String>) {
match self {
Children::Text(t) => {
*t = text;
}
_ => {}
}
/// 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
}
pub fn set_static(&mut self, text: String) {
*self = Children::StaticText(text);
/// 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
}
pub fn add_child(&mut self, element: Element) {
if let Children::Children(children, _) = self {
children.push(element);
/// 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());
}
pub fn get_child(&mut self) -> (Option<&mut Element>, usize) {
if let Children::Children(children, child) = self {
let l = children.len();
(children.get_mut(*child), l)
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 {
(None, 0)
}
}
pub fn get_child_idx(&mut self) -> (Option<(&mut Element, &mut usize)>, usize) {
if let Children::Children(children, child) = self {
let l = children.len();
if let Some(d) = children.get_mut(*child) {
(Some((d, child)), l)
} else {
(None, 0)
}
} else {
(None, 0)
}
}
pub fn set_index(&mut self, index: usize) {
if let Children::Children(_, child) = self {
*child = index;
}
}
pub fn len(&self) -> usize {
if let Children::Children(children, _) = self {
children.len()
} else {
0
}
}
pub fn index(&self) -> usize {
if let Children::Children(_, c) = self {
*c
} else {
0
}
}
pub fn index_mut(&mut self) -> Option<&mut usize> {
if let Children::Children(_, c) = self {
Some(c)
} else {
None
}
}
pub fn insert(&mut self, index: usize, element: Element) {
if let Children::Children(children, _) = self {
children.insert(index, element);
}
scope.clear();
if let Some(style) = elem.get() {
scope.set_style(style);
}
if let Some(t) = elem.get() {
scope.set_transform(&t);
}
impl<T> Handler<T> {
pub fn new<F>(handler_fn: F) -> Handler<T>
where
F: FnMut(&mut T, crossterm::event::Event, &mut Document) + 'static,
{
Handler(Arc::new(Mutex::new(handler_fn)))
for ext in self.extensions.lock().unwrap().iter() {
ext.lock().unwrap().render_widget(&mut scope, elem);
}
pub fn call(&self, s: &mut T, event: Event, document: &mut Document) {
let mut o = self.0.lock().unwrap();
o(s, event, document);
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);
}
pub fn clone(&self) -> Handler<T> {
Handler(Arc::clone(&self.0))
elem.auto_refresh();
}
Ok(())
}
impl Writer {
pub fn after_render(&self, width: u16, height: u16) {
if self.style.outline.1 {
let ol = self.style.write_outline("│");
let hl = "─".repeat(width as usize);
self.write_abs_outline(&self.style.write_outline(&format!("╭{}╮", hl)), (0, 0));
for i in 1..height+1 {
self.write_abs_outline(&ol, (0, i));
self.write_abs_outline(&ol, (width + 1, i));
}
self.write_abs_outline(&self.style.write_outline(&format!("╰{}╯", hl)), (0, height + 1));
}
}
/// Closes the loop and calls `on_close` in the extensions
pub fn close(self: &Arc<Self>) {
*self.running.lock().unwrap() = false;
pub fn write(&mut self, s: &str) {
self.write_abs(&self.style.write(&s), (0, 0));
}
utils::show_cursor().unwrap();
pub fn write_abs_outline(&self, s: &str, pos: (u16, u16)) {
if let Some(parent) = self.parent {
let parent = unsafe { &mut *parent };
parent.write_abs_outline(s, (self.pos.0 + pos.0, self.pos.1 + pos.1));
} else {
print!(
"\x1b[{};{}H{}",
self.pos.1 + pos.1 - 1,
self.pos.0 + pos.0 - 1,
self.style.write_outline(s)
);
}
}
utils::clear().unwrap();
pub fn write_abs(&mut self, s: &str, pos: (u16, u16)) {
let width = self.get_size().0 as usize;
let mut max_written = self.written.0;
let mut lines_written = 0;
let truncated_lines: Vec<_> = s
.lines()
.map(|l| {
let truncated = if l.len() > width {
l.chars().take(width).collect::<String>()
} else {
l.to_string()
};
max_written = max_written.max(truncated.visible_len() as u16);
lines_written += 1;
truncated
})
.collect();
self.written.0 = max_written;
self.written.1 += lines_written;
if let Some(parent) = self.parent {
let parent = unsafe { &mut *parent };
let combined_pos = (self.pos.0 + pos.0, self.pos.1 + pos.1);
let s_combined = truncated_lines.join("\n");
parent.write_abs(&s_combined, combined_pos);
} else {
for (i, line) in truncated_lines.iter().enumerate() {
print!(
"\x1b[{};{}H{}",
self.pos.1 + pos.1 + i as u16,
self.pos.0 + pos.0,
line
);
for ext in self.extensions.lock().unwrap().iter() {
ext.lock().unwrap().on_close(self.clone());
}
}
}
pub fn get_focused(&self) -> bool {
self.focused
}
pub fn get_size(&self) -> (u16, u16) {
(
self.style
.width
.1
.as_size(self.size.0, self.size.0, self.style.outline.1),
self.style
.height
.1
.as_size(self.size.1, self.size.1, self.style.outline.1),
)
}
pub fn get_size_root(&self) -> (u16, u16) {
(
self.style
.width
.1
.as_size(self.written.0, self.size.0, self.style.outline.1),
self.style
.height
.1
.as_size(self.written.1, self.size.1, self.style.outline.1),
)
}
pub fn new_frame(&mut self) -> crate::utils::Frame {
crate::utils::Frame::new(self)
}
pub fn caret(&self) -> String {
format!(
"{}{}\x1b[0m",
self.style.cursor.1.ansi(),
self.style.caret.1
)
}
}
impl<T> Default for Handler<T> {
fn default() -> Self {
Handler(Arc::new(Mutex::new(
|_: &mut T, _: crossterm::event::Event, _: &mut Document| {},
)))
}
}
impl<T> std::fmt::Debug for Handler<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Handler()")
}
}
impl<T> State<T> {
pub fn new<'a>(v: T) -> State<T> {
State(Arc::new(Mutex::new(v)))
}
pub fn use_state<'a>(&'a self) -> std::sync::MutexGuard<'a, T> {
self.0.lock().unwrap()
}
pub fn clone<'a>(&'a self) -> State<T> {
State(Arc::clone(&self.0))
}
}
impl<T: std::fmt::Display> std::fmt::Display for State<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Acquire the lock, handle potential poisoning
match self.0.lock() {
Ok(guard) => write!(f, "{}", *guard),
Err(poisoned) => write!(f, "<Poisoned: {}>", *poisoned.into_inner()),
}
}
}
impl<T: AddAssign> AddAssign<T> for State<T> {
fn add_assign(&mut self, rhs: T) {
*self.0.lock().unwrap() += rhs;
}
}
impl<T: SubAssign> SubAssign<T> for State<T> {
fn sub_assign(&mut self, rhs: T) {
*self.0.lock().unwrap() -= rhs;
}
}
impl<T: PartialEq> PartialEq<T> for State<T> {
fn eq(&self, other: &T) -> bool {
self.use_state().eq(other)
}
fn ne(&self, other: &T) -> bool {
self.use_state().ne(other)
}
}
#[derive(Debug)]
pub enum Instruction<'a> {
SetStyle(ui::Css),
SetChild(usize),
Ghost(usize),
Load(Handler<ui::Div<'a>>),
}
+295 -12
View File
@@ -1,18 +1,301 @@
/// 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! launch {
($elem:path) => {
let mut element = <$elem>::default().create_element();
let mut document = $crate::Document::with_elem(&mut element);
while document.run() {
element = <$elem>::default().create_element();
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
}
}
};
($elem:path, $css:expr) => {
let mut element = <$elem>::default().create_element();
let mut document = $crate::Document::with_elem(&mut element);
document.set_css($css);
while document.run() {
element = <$elem>::default().create_element();
($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_rules! rsx {
($($inner:tt)*) => {{
let mut r = $crate::frontend::Rsx(Vec::new());
$crate::rsx_inner! { r, $($inner)* };
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_rules! rsx_inner {
// static
($r:expr, $(@$comp:expr;)* static $s:literal $($rest:tt)*) => {
let w = $crate::widget::StaticWidget::new(Box::new(format!($s)));
$(w.component($comp);)*
$r.create_element_static(w, $crate::frontend::Rsx(Vec::new()));
$crate::rsx_inner! { $r, $($rest)* };
};
($r:expr, $(@$comp:expr;)* $(%$dep:ident)* $s:literal $($rest:tt)*) => {
$r.create_element({ $(let $dep = $dep.clone();)* move || {
$crate::widget::WidgetLoad::new(format!($s)) $(.component($comp))*
} }, vec![$(Box::new($dep.clone())),*], $crate::frontend::Rsx(Vec::new()));
$crate::rsx_inner! { $r, $($rest)* };
};
// static
($r:expr, $(@$comp:expr;)* static $name:path, $($f:ident $(: $v:expr)?),+, { $($inner:tt)* } $($rest:tt)*) => {
let w = $crate::widget::StaticWidget::new(Box::new({
let mut elem = <$name>::new();
$(elem.$f = $($v)?;)+
elem
}));
$(w.component($comp);)*
$r.create_element_static(w, $crate::rsx!{ $($inner)* });
$crate::rsx_inner! { $r, $($rest)* };
};
($r:expr, $(@$comp:expr;)* static $name:path { $($inner:tt)* } $($rest:tt)*) => {
let w = $crate::widget::StaticWidget::new(Box::new(<$name>::new()));
$(w.component($comp);)*
$r.create_element_static(w, $crate::rsx!{ $($inner)* });
$crate::rsx_inner! { $r, $($rest)* };
};
($r:expr, $(@$comp:expr;)* $(%$dep:ident)* $name:path, $($f:ident $(: $v:expr)?),+, { $($inner:tt)* } $($rest:tt)*) => {
$r.create_element({ $(let $dep = $dep.clone();)* move || {
$crate::widget::WidgetLoad::new({
let mut elem = <$name>::new();
$(elem.$f = $($v)?;)+
elem
}) $(.component($comp))*
} }, vec![$(Box::new($dep.clone())),*], $crate::rsx!{ $($inner)* });
$crate::rsx_inner! { $r, $($rest)* };
};
($r:expr, $(@$comp:expr;)* $(%$dep:ident)* $name:path { $($inner:tt)* } $($rest:tt)*) => {
$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_inner! { $r, $($rest)* };
};
($r:expr, $expand:ident => ($($inner:tt)*) $($rest:tt)*) => {
$r.expand(&mut $expand($($inner)*));
$crate::rsx_inner! { $r, $($rest)* };
};
($r:expr,) => {};
}
+7 -23
View File
@@ -1,27 +1,11 @@
use osui::{examples, prelude::*};
mod demos;
use osui::prelude::*;
fn main() {
launch!(App);
}
fn main() -> std::io::Result<()> {
let screen = Screen::new();
screen.extension(InputExtension);
#[component]
fn App() {
rsx! {
@SetStyle(css! {
example: "hover" {
color: Blue,
}
})
demos::app(screen.clone()).draw(&screen);
%text { "Choose an example to run" }
button { class: "example", on_click: |_, _, doc| {
doc.draw(examples::counter_example::App::default().create_element());
}, "Counter" }
button { class: "example", on_click: |_, _, doc| {
doc.draw(examples::login_example::App::default().create_element());
}, "Login" }
button { class: "example", on_click: |_, _, doc| {
doc.draw(examples::todo_example::App::default().create_element());
}, "Todo" }
}
screen.run()
}
+300
View File
@@ -0,0 +1,300 @@
//! 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")
}
}
-153
View File
@@ -1,153 +0,0 @@
#[macro_export]
macro_rules! check_expr {
(|| $code:block) => {
$crate::Handler::new(move |_, _, _| $code)
};
(|$($inner:tt)*| $code:block) => {
$crate::Handler::new(move |$($inner)*| $code)
};
($expr:expr) => {
$expr
};
}
#[macro_export]
macro_rules! parse_rsx_param {
//// FUNCTIONS
($elem:expr, $($k:ident).+: fn($($params:tt)*) $(@$($v:ident),+)? $body:expr $(, $($rest:tt)*)?) => {
$elem.$($k).+ = $crate::Handler::new({
$($(
#[allow(unused_mut)]
let mut $v = $v.clone();
)+)?
move |$($params)*| {
$body
}
});
osui::parse_rsx_param!($elem, $($($rest)*)?);
};
($elem:expr, $($k:ident).+: |$($args:tt $(: $aty:ty)?),*| $(@$($v:ident),+)? $body:expr $(, $($rest:tt)*)?) => {
$elem.$($k).+ = $crate::Handler::new({
$($(
#[allow(unused_mut)]
let mut $v = $v.clone();
)+)?
move |$($args $(: $aty)?),*| $body
});
osui::parse_rsx_param!($elem, $($($rest)*)?);
};
//// FUNCTIONS END
($elem:expr, async $code:block $($rest:tt)*) => {
let elem_len = $elem.children.len();
$elem.instructions.push($crate::Instruction::Load(Handler::new(
move |d: &mut Div, _, _| {
d.children.insert(elem_len, $code);
}
)));
osui::parse_rsx_param!($elem, $($rest)*);
};
($elem:expr, %$elem_path:path { $($inner:tt)* } $($rest:tt)*) => {
$elem.ghosts.push($elem.ghosts.len());
if let $crate::Children::Children(children, _) = &mut $elem.children {
children.push($crate::ersx!($elem_path { $($inner)* }));
} else {
$elem.children = $crate::Children::Children(vec![$crate::ersx!($elem_path { $($inner)* })], 0)
}
osui::parse_rsx_param!($elem, $($rest)*)
};
($elem:expr, @ $($i:ident)::+($($inner:tt)*) $($rest:tt)*) => {
$elem.instructions.push($($i)::+($($inner)*));
osui::parse_rsx_param!($elem, $($rest)*);
};
($elem:expr, @ $($i:ident)::+ $($rest:tt)*) => {
$elem.instructions.push($($i)::+);
osui::parse_rsx_param!($elem, $($rest)*);
};
($elem:expr, static $text:literal $($other:tt)*) => {
$elem.children = $crate::Children::StaticText(format!($text $($other)*));
};
($elem:expr, for ($($for:tt)*) $code:block $($rest:tt)*) => {
if $elem.children.is_none() {$elem.children = $crate::Children::Children(Vec::new(), 0)}
if let $crate::Children::Children(children, _) = &mut $elem.children {
for $($for)* {
children.push($code)
}
}
osui::parse_rsx_param!($elem, $($rest)*);
};
($elem:expr, $($k:ident).+: $v:expr $(, $($rest:tt)*)?) => {
$elem.$($k).+ = $crate::check_expr!($v);
osui::parse_rsx_param!($elem, $($($rest)*)?);
};
($elem:expr, $p:path) => {
$p;
};
($elem:expr, $($k:ident).+, $($rest:tt)*) => {
$elem.$($k).+ = !$elem.$($k).+;
osui::parse_rsx_param!($elem, $($rest)*);
};
($elem:expr, $code:block $($rest:tt)*) => {
if $elem.children.is_none() {$elem.children = $crate::Children::Children(Vec::new(), 0)}
if let $crate::Children::Children(children, _) = &mut $elem.children {
children.push($code);
}
osui::parse_rsx_param!($elem, $($rest)*);
};
($elem:expr, $elem_path:path { $($inner:tt)* } $($rest:tt)*) => {
if let $crate::Children::Children(children, _) = &mut $elem.children {
children.push($crate::ersx!($elem_path { $($inner)* }));
} else {
$elem.children = $crate::Children::Children(vec![$crate::ersx!($elem_path { $($inner)* })], 0)
}
osui::parse_rsx_param!($elem, $($rest)*)
};
($elem:expr, $text:literal $($other:tt)*) => {
$elem.children = $crate::Children::Text(
std::sync::Arc::new(move || format!($text $($other)*))
);
};
($elem:expr,) => {};
}
#[macro_export]
macro_rules! ersx {
($elem:path { $($inner:tt)* }) => {{
let mut elem = <$elem>::default();
$crate::parse_rsx_param!(elem, $($inner)*);
elem.create_element()
}};
}
/// Makes a div and puts elements into it
///
/// # Example
/// ```
/// rsx! {
/// button { class: "btn", "Click me!" }
/// }
/// ```
///
/// # Returns
/// A `osui::Element` - Which is a `Box<dyn osui::ElementWidget>`
#[macro_export]
macro_rules! rsx {
($($inner:tt)*) => {
$crate::ersx!{ $crate::ui::div { $($inner)* } }
};
}
+100
View File
@@ -0,0 +1,100 @@
use std::{
fmt::{Debug, Display, Formatter, Result as FmtResult},
ops::{Deref, DerefMut},
sync::{Arc, Mutex, MutexGuard},
};
/// Trait for tracking dependencies and reactivity.
pub trait DependencyHandler: std::fmt::Debug + Send + Sync {
/// Called when a dependent is registered.
fn add(&self);
/// Returns `true` if the state has changed since the last check.
fn check(&self) -> bool;
}
#[derive(Debug, Clone)]
pub struct State<T> {
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> {
State {
inner: Arc::new(Mutex::new(Inner {
value: v,
dependencies: 0,
changed: 0,
})),
}
}
impl<T: Clone> State<T> {
/// Gets the cloned value, recommended for preventing deadlocks
pub fn get_dl(&self) -> T {
self.inner.lock().unwrap().value.clone()
}
}
impl<T> State<T> {
/// Gets a lock on the state for read/write access.
pub fn get(&self) -> MutexGuard<'_, Inner<T>> {
self.inner.lock().unwrap()
}
/// Sets the value and marks it as changed.
pub fn set(&self, v: T) {
let mut inner = self.inner.lock().unwrap();
inner.value = v;
inner.changed = inner.dependencies;
}
/// Marks the state as updated.
pub fn update(&self) {
let mut inner = self.inner.lock().unwrap();
inner.changed = inner.dependencies;
}
}
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) {
let mut inner = self.inner.lock().unwrap();
inner.dependencies += 1;
}
}
impl<T: Display> Display for State<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
let inner = self.inner.lock().unwrap();
write!(f, "{}", inner.value)
}
}
impl<T> Deref for Inner<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T> DerefMut for Inner<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.changed = self.dependencies;
&mut self.value
}
}
+228
View File
@@ -0,0 +1,228 @@
//! 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)
}
}
-267
View File
@@ -1,267 +0,0 @@
/// The `ui` module defines the basic building blocks for creating a terminal-based UI framework.
///
/// # Modules
/// - `styles`: A module for defining UI styles.
pub mod styles;
pub use styles::*;
use crate::prelude::*;
use osui_element::element;
#[element]
#[derive(Default, Debug)]
pub struct Text {}
impl ElementWidget for Text<'_> {
fn render(&self, writer: &mut crate::Writer) {
writer.write(&self.children.get_text());
}
}
#[component]
pub fn text<'a>(class: &'a str, id: &'a str, children: Children, style: Style) -> Box<Text<'a>> {
Box::new(Text {
class: self.class,
id: self.id,
children: self.children,
style: self.style,
})
}
#[element]
#[derive(Default, Debug)]
pub struct Div {
pub instructions: Vec<crate::Instruction<'a>>,
pub ghosts: Vec<usize>,
}
impl ElementWidget for Div<'_> {
fn render(&self, writer: &mut crate::Writer) {
let focused = writer.get_focused();
let mut frame = writer.new_frame();
if let Children::Children(children, child) = &self.children {
for (i, elem) in children.iter().enumerate() {
frame.render(focused && i == *child, elem);
}
}
}
fn event(&mut self, event: Event, document: &mut Document) {
if let (Some((child, i)), l) = self.children.get_child_idx() {
match event {
Event::Key(k) => match k.code {
KeyCode::Tab => {
child.event(Event::FocusLost, document);
if *i < l - 1 {
*i += 1;
} else {
*i = 0;
}
while self.ghosts.get(*i).is_some() {
if *i < l - 1 {
*i += 1;
} else {
*i = 0;
}
}
child.event(Event::FocusGained, document);
}
KeyCode::BackTab => {
child.event(Event::FocusLost, document);
if *i > 0 {
*i -= 1;
} else {
*i = l - 1;
}
while self.ghosts.get(*i).is_some() {
if *i > 0 {
*i -= 1;
} else {
*i = l - 1;
}
}
child.event(Event::FocusGained, document);
}
_ => child.event(event, document),
},
_ => child.event(event, document),
}
}
}
fn initialize(&mut self, document: &mut Document) {
let l = self.children.len();
if let Some(i) = self.children.index_mut() {
while self.ghosts.get(*i).is_some() {
if *i < l - 1 {
*i += 1;
} else {
*i = 0;
break;
}
}
}
let mut load_funcs = Vec::new();
for inst in &self.instructions {
match inst {
crate::Instruction::SetStyle(s) => {
document.css.extend(s.clone().into_iter());
}
crate::Instruction::SetChild(c) => {
self.children.set_index(*c);
}
crate::Instruction::Ghost(idx) => {
self.ghosts.push(*idx);
}
crate::Instruction::Load(f) => {
load_funcs.push(f.clone());
}
}
}
self.instructions.clear();
for i in load_funcs {
i.call(self, Event::FocusGained, document)
}
}
}
#[component]
pub fn div<'a>(
class: &'a str,
id: &'a str,
children: Children,
style: Style,
instructions: Vec<crate::Instruction<'a>>,
ghosts: Vec<usize>,
) -> Box<Div<'a>> {
Box::new(Div {
children: self.children,
class: self.class,
id: self.id,
style: self.style,
instructions: self.instructions,
ghosts: self.ghosts,
})
}
#[element]
#[derive(Default, Debug)]
pub struct Button {
pub on_click: Handler<Button<'a>>,
pub on_hover: Handler<Button<'a>>,
}
impl ElementWidget for Button<'_> {
fn render(&self, writer: &mut crate::Writer) {
writer.write(&self.children.get_text());
}
fn event(&mut self, event: Event, document: &mut Document) {
match event {
Event::Key(key) => {
if key.code == KeyCode::Enter {
document.render();
self.style.set_state("clicked");
self.on_click.clone().call(self, event, document);
document.render();
sleep(65);
self.style.set_state("");
}
}
Event::FocusGained => {
self.on_hover.clone().call(self, event, document);
}
_ => {}
}
}
}
#[component]
pub fn button<'a>(
class: &'a str,
id: &'a str,
children: Children,
style: Style,
on_click: Handler<Button<'a>>,
on_hover: Handler<Button<'a>>,
) -> Box<Button<'a>> {
Box::new(Button {
class: self.class,
id: self.id,
children: self.children,
on_click: self.on_click.clone(),
on_hover: self.on_hover.clone(),
style: self.style,
})
}
#[element]
#[derive(Default, Debug)]
pub struct Input {
pub on_click: Handler<Input<'a>>,
pub text: String,
pub placeholder: &'a str,
}
impl ElementWidget for Input<'_> {
fn render(&self, writer: &mut crate::Writer) {
if self.text.is_empty() {
writer.write(&format!(
"{}{}{}",
self.children.get_text(),
self.placeholder,
writer.caret()
));
} else {
writer.write(&format!(
"{}{}{}",
self.children.get_text(),
self.text,
writer.caret()
));
}
}
fn event(&mut self, event: crossterm::event::Event, document: &mut Document) {
match event {
Event::Key(k) => match k.code {
KeyCode::Backspace => {
if self.text.len() > 0 {
self.text.pop();
}
}
KeyCode::Enter => {
self.on_click.clone().call(self, event, document);
}
KeyCode::Char(c) => {
self.text.push(c);
}
_ => {}
},
_ => {}
}
}
}
#[component]
pub fn input<'a>(
class: &'a str,
id: &'a str,
placeholder: &'a str,
text: String,
children: Children,
style: Style,
on_click: Handler<Input<'a>>,
) -> Box<Input<'a>> {
Box::new(Input {
class: self.class,
id: self.id,
children: self.children,
style: self.style,
on_click: self.on_click,
placeholder: self.placeholder,
text: self.text,
})
}
-347
View File
@@ -1,347 +0,0 @@
//! The `styles` module defines various styling options for UI elements. This includes colors,
//! fonts, padding, margins, and other visual properties that can be applied to UI components
//! to change their appearance.
use std::{collections::HashMap, fmt::Debug};
use dyn_clone::{clone_trait_object, DynClone};
//////////////////////////////////////////////////////////////////////////////////////////////////
// Type aliases
//////////////////////////////////////////////////////////////////////////////////////////////////
pub type Css = HashMap<StyleName, StyleElement>;
//////////////////////////////////////////////////////////////////////////////////////////////////
// Traits
//////////////////////////////////////////////////////////////////////////////////////////////////
pub trait StyleCore: Debug + Send + Sync + DynClone {
fn ansi(&self) -> String;
fn ansi_bg(&self) -> String;
}
clone_trait_object!(StyleCore);
//////////////////////////////////////////////////////////////////////////////////////////////////
// Enums
//////////////////////////////////////////////////////////////////////////////////////////////////
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Font {
Bold,
Underline,
Italic,
Reverse,
Strike,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Color {
NoColor,
Rgb(u8, u8, u8),
Hex(String),
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Number {
Px(u16),
Pe(u16),
Center,
Auto,
}
#[derive(PartialEq, Eq, Hash, Debug, Clone)]
pub enum StyleName {
Class(String),
ClassState(String, String),
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Structs
//////////////////////////////////////////////////////////////////////////////////////////////////
#[derive(Debug, Clone)]
pub struct StyleElement {
pub color: (bool, Color),
pub background: (bool, Color),
pub outline_color: (bool, Color),
pub font: (bool, Vec<Font>),
pub x: (bool, Number),
pub y: (bool, Number),
pub width: (bool, Number),
pub height: (bool, Number),
pub visible: (bool, bool),
pub outline: (bool, bool),
pub cursor: (bool, Color),
pub caret: (bool, String),
}
#[derive(Debug, Clone)]
pub struct Style(
pub StyleElement,
pub HashMap<String, StyleElement>,
pub String,
);
//////////////////////////////////////////////////////////////////////////////////////////////////
// Implementations
//////////////////////////////////////////////////////////////////////////////////////////////////
impl Default for Style {
fn default() -> Self {
Style(StyleElement::default(), HashMap::new(), String::new())
}
}
impl Style {
pub fn get(mut self, hover: bool) -> StyleElement {
if let Some(style_element) = self.1.get(&self.2) {
self.0.merge(style_element);
self.0
} else if hover {
if let Some(style_element) = self.1.get("hover") {
self.0.merge(style_element);
self.0
} else {
self.0
}
} else {
self.0
}
}
pub fn set_state(&mut self, state: &str) {
self.2 = state.to_string();
}
}
impl StyleElement {
pub fn write(&self, s: &str) -> String {
s.split('\n')
.into_iter()
.map(|p| {
format!(
"{}{}{}{p}\x1b[0m",
self.color.1.ansi(),
self.background.1.ansi_bg(),
self.font.1.ansi()
)
})
.collect::<Vec<String>>()
.join("\n")
}
pub fn write_outline(&self, outline: &str) -> String {
format!("{}{outline}\x1b[0m", self.outline_color.1.ansi(),)
}
}
impl Default for StyleElement {
fn default() -> Self {
StyleElement {
color: (false, Color::NoColor),
background: (false, Color::NoColor),
cursor: (false, Color::NoColor),
font: (false, Vec::new()),
outline_color: (false, Color::NoColor),
x: (false, Number::Px(0)),
y: (false, Number::Auto),
width: (false, Number::Auto),
height: (false, Number::Auto),
visible: (false, true),
outline: (false, false),
caret: (false, String::from("█")),
}
}
}
impl StyleElement {
pub fn merge(&mut self, upper: &Self) {
if upper.color.0 {
self.color = upper.color.clone();
}
if upper.background.0 {
self.background = upper.background.clone();
}
if upper.font.0 {
self.font = upper.font.clone();
}
if upper.outline_color.0 {
self.outline_color = upper.outline_color.clone();
}
if upper.x.0 {
self.x = upper.x.clone();
}
if upper.y.0 {
self.y = upper.y.clone();
}
if upper.width.0 {
self.width = upper.width.clone();
}
if upper.height.0 {
self.height = upper.height.clone();
}
if upper.visible.0 {
self.visible = upper.visible.clone();
}
if upper.outline.0 {
self.outline = upper.outline.clone();
}
if upper.cursor.0 {
self.cursor = upper.cursor.clone();
}
if upper.caret.0 {
self.caret = upper.caret.clone();
}
}
}
impl StyleCore for Color {
fn ansi(&self) -> String {
String::from(match self {
Color::NoColor => "",
Color::Rgb(r, g, b) => {
return format!("\x1b[38;2;{r};{g};{b}m");
}
Color::Hex(hex) => {
let (r, g, b) = hex_to_rgb(hex);
return format!("\x1b[38;2;{r};{g};{b}m");
}
Color::Black => "\x1b[30m",
Color::Red => "\x1b[31m",
Color::Green => "\x1b[32m",
Color::Yellow => "\x1b[33m",
Color::Blue => "\x1b[34m",
Color::Magenta => "\x1b[35m",
Color::Cyan => "\x1b[36m",
Color::White => "\x1b[37m",
})
}
fn ansi_bg(&self) -> String {
String::from(match self {
Color::NoColor => "",
Color::Rgb(r, g, b) => {
return format!("\x1b[48;2;{r};{g};{b}m");
}
Color::Hex(hex) => {
let (r, g, b) = hex_to_rgb(hex);
return format!("\x1b[48;2;{r};{g};{b}m");
}
Color::Black => "\x1b[40m",
Color::Red => "\x1b[41m",
Color::Green => "\x1b[42m",
Color::Yellow => "\x1b[43m",
Color::Blue => "\x1b[44m",
Color::Magenta => "\x1b[45m",
Color::Cyan => "\x1b[46m",
Color::White => "\x1b[47m",
})
}
}
impl Default for Color {
fn default() -> Self {
Color::NoColor
}
}
fn hex_to_rgb(hex: &str) -> (u8, u8, u8) {
let hex = hex.trim_start_matches('#');
let hex = if hex.len() == 3 {
format!(
"{}{}{}{}{}{}",
&hex[0..1],
&hex[0..1],
&hex[1..2],
&hex[1..2],
&hex[2..3],
&hex[2..3]
)
} else if hex.len() == 6 {
hex.to_string()
} else {
return (255, 255, 255);
};
let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(255);
let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(255);
let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(255);
(r, g, b)
}
impl StyleCore for Font {
fn ansi(&self) -> String {
String::from(match self {
Font::Bold => "\x1b[1m",
Font::Underline => "\x1b[4m",
Font::Italic => "\x1b[3m",
Font::Reverse => "\x1b[7m",
Font::Strike => "\x1b[9m",
})
}
fn ansi_bg(&self) -> String {
self.ansi()
}
}
impl StyleCore for Vec<Font> {
fn ansi(&self) -> String {
let mut a = String::new();
for i in self {
a += i.ansi().as_str();
}
a
}
fn ansi_bg(&self) -> String {
let mut a = String::new();
for i in self {
a += i.ansi_bg().as_str();
}
a
}
}
impl Number {
pub fn as_size_raw(&self, frame_size: u16) -> u16 {
match self {
Number::Px(s) => *s,
Number::Pe(pe) => (frame_size * pe) / 100,
_ => frame_size,
}
}
pub fn as_size(&self, written: u16, frame_size: u16, outline: bool) -> u16 {
if *self == Number::Auto {
written
} else if outline {
self.as_size_raw(frame_size) - 2
} else {
self.as_size_raw(frame_size)
}
}
pub fn as_position_raw(&self, used: &u16, frame_size: u16) -> u16 {
match self {
crate::ui::Number::Px(px) => *px,
crate::ui::Number::Pe(pe) => (frame_size * pe) / 100,
crate::ui::Number::Center => (frame_size) / 2,
crate::ui::Number::Auto => *used,
}
}
pub fn as_position(&self, outline: bool, used: &u16, frame_size: u16) -> u16 {
if outline {
self.as_position_raw(used, frame_size) + 1
} else {
self.as_position_raw(used, frame_size)
}
}
}
+102 -113
View File
@@ -1,133 +1,122 @@
use std::io::{stdout, Write};
//! The `utils` module provides utility functions for terminal manipulation
//! and string operations, designed to enhance terminal-based applications.
pub struct Frame<'a> {
used: Vec<u16>,
writer: &'a mut crate::Writer,
}
use std::io::{self, Write};
impl<'a> Frame<'a> {
pub fn new(writer: &'a mut crate::Writer) -> Self {
Frame {
used: vec![0; writer.size.1 as usize],
writer,
}
}
pub fn render(&mut self, focused: bool, element: &crate::Element) {
let style = element.get_style();
let mut style_element = style.clone().get(focused);
let css = unsafe { &*self.writer.css };
for class in element.get_class().split(" ") {
if let Some(upper) = css.get(&crate::ui::StyleName::Class(class.to_string())) {
style_element.merge(upper);
}
if let Some(upper) = css.get(&crate::ui::StyleName::ClassState(
class.to_string(),
if style.2 == "" && focused {
"hover".to_string()
} else {
style.2.clone()
},
)) {
style_element.merge(upper);
}
}
if !style_element.visible.1 {
return;
}
let y = style_element.y.1.as_position(
style_element.outline.1,
&{
let mut y = 0;
while y < self.used.len() && self.used[y] != 0 {
y += 1;
}
y as u16
},
self.writer.size.1,
);
if let Some(y_) = self.used.get(y as usize) {
let x = style_element
.x
.1
.as_position(style_element.outline.1, y_, self.writer.size.0);
let mut writer = crate::Writer {
focused,
style: style_element.clone(),
pos: (x, y),
size: self.writer.size,
css,
parent: Some(self.writer),
written: (0, 0),
};
element.render(&mut writer);
let (width, height) = writer.get_size_root();
{
let (x, y, width, height) = if style_element.outline.1 {
(x - 1, y - 1, width + 2, height + 2)
} else {
(x, y, width, height)
};
for i in y..y + height {
if let Some(o) = self.used.get_mut(i as usize) {
if style_element.x.1 != crate::ui::Number::Auto {
*o += x;
}
*o += width;
}
}
}
writer.after_render(width, height);
}
}
}
pub fn clear() {
/// 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");
stdout().flush().unwrap();
std::io::stdout().flush()
}
pub fn hide_cursor() {
/// 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");
stdout().flush().unwrap();
std::io::stdout().flush()
}
pub fn show_cursor() {
/// 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");
stdout().flush().unwrap();
std::io::stdout().flush()
}
pub fn flush() {
stdout().flush().unwrap();
/// 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()
}
pub trait VisibleLength {
fn visible_len(&self) -> usize;
}
/// 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;
impl VisibleLength for String {
fn visible_len(&self) -> usize {
let mut length = 0;
let mut in_escape = false;
for c in self.chars() {
if c == '\x1b' {
in_escape = true;
} else if in_escape {
if c.is_ascii_alphabetic() {
in_escape = false;
}
for b in s.bytes() {
if b == b'\n' {
height += 1;
max_width = max_width.max(current_width);
current_width = 0;
} else {
length += 1;
current_width += 1;
}
}
length
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
View File
@@ -0,0 +1,362 @@
//! 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)
}
}
-9
View File
@@ -1,9 +0,0 @@
`color`, `background`: `$color{}\x1b[0m`;
`font`: `$font{}\x1b[0m`;
`width`, `height`: `n`, `n%`, `auto`;
`x`, `y`: `n`, `n%`, `center`, `auto`;
<!-- `display`: `row`, `column`, `overlap`; -->