Compare commits
46
Commits
v0.0.9-alpha-2
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6569a9eb20 | ||
|
|
2c7d3cc80f | ||
|
|
2383a7b42a | ||
|
|
d59c3d7911 | ||
|
|
1aa78bc1a4 | ||
|
|
f8f924ce25 | ||
|
|
ea9afb0e64 | ||
|
|
71299046d3 | ||
|
|
acce51c372 | ||
|
|
ba04a82980 | ||
|
|
ec3576e6db | ||
|
|
e0ae338e15 | ||
|
|
d2757ad7b0 | ||
|
|
de039fac96 | ||
|
|
2d8755b13c | ||
|
|
d9d107bd80 | ||
|
|
35dcc4d22c | ||
|
|
34b5799644 | ||
|
|
911968a1cb | ||
|
|
d00fbb6565 | ||
|
|
2892176a76 | ||
|
|
36e06732d9 | ||
|
|
3a4c3505ac | ||
|
|
0ccf03de3b | ||
|
|
48849c7cc2 | ||
|
|
2b0d85549f | ||
|
|
598ab5b54d | ||
|
|
095aa14b82 | ||
|
|
d1008a69c9 | ||
|
|
a30afdeb28 | ||
|
|
1debb6a576 | ||
|
|
fc0406e412 | ||
|
|
27580e773a | ||
|
|
a1499064ac | ||
|
|
c2563358b6 | ||
|
|
b45ef950a1 | ||
|
|
063c90d986 | ||
|
|
da1ecb1f21 | ||
|
|
75827260cc | ||
|
|
9a91fb3af0 | ||
|
|
bbff192788 | ||
|
|
73e2c214ee | ||
|
|
45db1fb774 | ||
|
|
af5428a2f3 | ||
|
|
b227f19a9c | ||
|
|
ae16c9a69e |
@@ -0,0 +1,5 @@
|
||||
debug
|
||||
target
|
||||
github
|
||||
Cargo.lock
|
||||
.DS_Store
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "osui"
|
||||
version = "0.0.9-alpha.2"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "A TUI library for advanced uis"
|
||||
@@ -25,6 +25,7 @@ cc = "1.0"
|
||||
|
||||
[dependencies]
|
||||
crossterm = "0.28.1"
|
||||
figlet-rs = "0.1.5"
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
|
||||
@@ -21,14 +21,15 @@
|
||||
</p>
|
||||
|
||||
```rust
|
||||
use osui::{style::Transform, Screen};
|
||||
use osui::prelude::*;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
let screen = Screen::new();
|
||||
|
||||
screen
|
||||
.draw(format!("Hello, World"))
|
||||
.component(Transform::center());
|
||||
rsx! {
|
||||
"Hello, World"
|
||||
}
|
||||
.draw(&screen);
|
||||
|
||||
screen.run()
|
||||
}
|
||||
|
||||
@@ -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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
-26
@@ -1,20 +1,28 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
widget::{Element, Widget},
|
||||
NoRender,
|
||||
NoRender, NoRenderRoot,
|
||||
};
|
||||
|
||||
pub struct Div {
|
||||
color: u32,
|
||||
children: Mutex<Vec<Arc<Widget>>>,
|
||||
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.draw_rect(width, height, self.color);
|
||||
scope.use_area(width, height);
|
||||
}
|
||||
|
||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
@@ -22,32 +30,39 @@ impl Element for Div {
|
||||
let (w, h) = scope.get_parent_size();
|
||||
scope.set_parent_size(transform.width, transform.height);
|
||||
|
||||
for elem in self.children.lock().unwrap().iter() {
|
||||
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.0.lock().unwrap().render(scope);
|
||||
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);
|
||||
transform.height = transform.height.max(t.y + t.height);
|
||||
t.x += transform.x;
|
||||
t.y += transform.y;
|
||||
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.0.lock().unwrap().after_render(scope);
|
||||
scope.clear();
|
||||
elem.get_elem().after_render(scope);
|
||||
}
|
||||
scope.set_parent_size(w, h);
|
||||
self.size = (transform.width, transform.height);
|
||||
}
|
||||
|
||||
fn draw_child(&self, element: &Arc<Widget>) {
|
||||
self.children.lock().unwrap().push(element.clone());
|
||||
element.inject(|w| w.component(NoRender));
|
||||
fn 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 {
|
||||
@@ -58,13 +73,3 @@ impl Element for Div {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Div {
|
||||
pub fn new(color: u32) -> Self {
|
||||
Div {
|
||||
color,
|
||||
children: Mutex::new(Vec::new()),
|
||||
size: (0, 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+65
-48
@@ -1,25 +1,46 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{widget::{Element, Widget}, NoRender};
|
||||
use crate::{
|
||||
widget::{Element, Widget},
|
||||
NoRender, NoRenderRoot,
|
||||
};
|
||||
|
||||
pub struct FlexRow {
|
||||
color: u32,
|
||||
gap: u16,
|
||||
children: Mutex<Vec<Arc<Widget>>>,
|
||||
pub gap: u16,
|
||||
children: Vec<Arc<Widget>>,
|
||||
size: (u16, u16),
|
||||
}
|
||||
|
||||
pub struct FlexCol {
|
||||
color: u32,
|
||||
gap: u16,
|
||||
children: Mutex<Vec<Arc<Widget>>>,
|
||||
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.draw_rect(width, height, self.color);
|
||||
scope.use_area(width, height);
|
||||
}
|
||||
|
||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
@@ -29,12 +50,19 @@ impl Element for FlexRow {
|
||||
|
||||
let mut v = 0;
|
||||
|
||||
for elem in self.children.lock().unwrap().iter() {
|
||||
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.0.lock().unwrap().render(scope);
|
||||
elem.get_elem().render(scope);
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
@@ -43,19 +71,21 @@ impl Element for FlexRow {
|
||||
transform.height = transform.height.max(v + t.height);
|
||||
t.x += transform.x;
|
||||
t.y += transform.y + v;
|
||||
v += t.height + self.gap;
|
||||
v += t.height + self.gap + (t.py * 2);
|
||||
t.px += transform.px;
|
||||
t.py += transform.py;
|
||||
|
||||
scope.draw();
|
||||
|
||||
elem.0.lock().unwrap().after_render(scope);
|
||||
elem.get_elem().after_render(scope);
|
||||
}
|
||||
scope.set_parent_size(w, h);
|
||||
self.size = (transform.width, transform.height);
|
||||
}
|
||||
|
||||
fn draw_child(&self, element: &Arc<Widget>) {
|
||||
self.children.lock().unwrap().push(element.clone());
|
||||
element.inject(|w| w.component(NoRender));
|
||||
fn 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 {
|
||||
@@ -67,21 +97,10 @@ impl Element for FlexRow {
|
||||
}
|
||||
}
|
||||
|
||||
impl FlexRow {
|
||||
pub fn new(color: u32, gap: u16) -> Self {
|
||||
Self {
|
||||
children: Mutex::new(Vec::new()),
|
||||
size: (0, 0),
|
||||
color,
|
||||
gap,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for FlexCol {
|
||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
let (width, height) = scope.get_size_or(self.size.0, self.size.1);
|
||||
scope.draw_rect(width, height, self.color);
|
||||
scope.use_area(width, height);
|
||||
}
|
||||
|
||||
fn after_render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
@@ -91,33 +110,42 @@ impl Element for FlexCol {
|
||||
|
||||
let mut v = 0;
|
||||
|
||||
for elem in self.children.lock().unwrap().iter() {
|
||||
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.0.lock().unwrap().render(scope);
|
||||
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);
|
||||
transform.height = transform.height.max(t.height);
|
||||
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;
|
||||
v += t.width + self.gap + (t.px * 2);
|
||||
t.px += transform.px;
|
||||
t.py += transform.py;
|
||||
|
||||
scope.draw();
|
||||
|
||||
elem.0.lock().unwrap().after_render(scope);
|
||||
elem.get_elem().after_render(scope);
|
||||
}
|
||||
scope.set_parent_size(w, h);
|
||||
self.size = (transform.width, transform.height);
|
||||
}
|
||||
|
||||
fn draw_child(&self, element: &Arc<Widget>) {
|
||||
self.children.lock().unwrap().push(element.clone());
|
||||
element.inject(|w| w.component(NoRender));
|
||||
fn 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 {
|
||||
@@ -128,14 +156,3 @@ impl Element for FlexCol {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl FlexCol {
|
||||
pub fn new(color: u32, gap: u16) -> Self {
|
||||
Self {
|
||||
children: Mutex::new(Vec::new()),
|
||||
size: (0, 0),
|
||||
color,
|
||||
gap,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -1,16 +1,20 @@
|
||||
pub mod div;
|
||||
pub mod flex;
|
||||
pub mod shape;
|
||||
pub mod heading;
|
||||
pub mod input;
|
||||
pub mod paginator;
|
||||
|
||||
pub use div::*;
|
||||
pub use flex::*;
|
||||
pub use shape::*;
|
||||
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(self);
|
||||
scope.draw_text(0, 0, self);
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
@@ -24,7 +28,7 @@ impl Element for String {
|
||||
|
||||
impl Element for (String, u32) {
|
||||
fn render(&mut self, scope: &mut crate::render_scope::RenderScope) {
|
||||
scope.draw_text_colored(&self.0, self.1);
|
||||
scope.draw_text_colored(0, 0, &self.0, self.1);
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
use crate::widget::Element;
|
||||
|
||||
pub struct RoundedOutline;
|
||||
|
||||
impl Element for RoundedOutline {
|
||||
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
|
||||
let (w, h) = scope.get_size_or_parent();
|
||||
if w > 2 && h > 2 {
|
||||
let d = "─".repeat(w as usize - 2);
|
||||
scope.draw_text(&format!(
|
||||
"╭{d}╮{}\n╰{d}╯",
|
||||
format!("\n│{}│", " ".repeat(w as usize - 2)).repeat(h as usize - 2),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RoundedOutline {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Outline;
|
||||
|
||||
impl Element for Outline {
|
||||
fn render(&mut self, scope: &mut crate::prelude::RenderScope) {
|
||||
let (w, h) = scope.get_size_or_parent();
|
||||
if w > 2 && h > 2 {
|
||||
let d = "─".repeat(w as usize - 2);
|
||||
scope.draw_text(&format!(
|
||||
"┌{d}┐{}\n└{d}┘",
|
||||
format!("\n│{}│", " ".repeat(w as usize - 2)).repeat(h as usize - 2),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ 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 {
|
||||
@@ -23,5 +25,3 @@ impl IdExtension {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
component!(Id(pub usize));
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
pub mod id;
|
||||
pub mod resources;
|
||||
pub mod input_handling;
|
||||
pub mod tick;
|
||||
pub mod velocity;
|
||||
|
||||
pub use id::*;
|
||||
pub use resources::*;
|
||||
pub use input_handling::*;
|
||||
pub use tick::*;
|
||||
pub use velocity::*;
|
||||
|
||||
@@ -22,6 +22,7 @@ use crate::{
|
||||
|
||||
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>) {}
|
||||
}
|
||||
|
||||
@@ -57,3 +58,9 @@ impl<E: Event> Debug for Handler<E> {
|
||||
write!(f, "Handler({})", type_name::<E>())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> dyn Event + 'a {
|
||||
pub fn get<T: Event + 'static>(&self) -> Option<&T> {
|
||||
self.as_any().downcast_ref()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct VecResource<T>(Arc<Mutex<Box<dyn FnMut(&T) + Send + Sync>>>);
|
||||
|
||||
impl<T: Send + Sync + 'static> VecResource<T> {
|
||||
pub fn new() -> Self {
|
||||
Self(Arc::new(Mutex::new(Box::new(|_| {}))))
|
||||
}
|
||||
|
||||
pub fn iterate<F: FnMut(&T) + Send + Sync + 'static>(&self, f: F) {
|
||||
*self.0.lock().unwrap() = Box::new(f);
|
||||
}
|
||||
|
||||
pub fn push(&self, e: T) {
|
||||
let i = self.0.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
(i.lock().unwrap())(&e);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
use std::{fmt::Debug, sync::Arc};
|
||||
|
||||
use crate::extensions::Extension;
|
||||
use crate::extensions::Handler;
|
||||
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;
|
||||
@@ -14,9 +15,7 @@ impl Extension for TickExtension {
|
||||
let mut tick = 0;
|
||||
loop {
|
||||
for w in screen.widgets.lock().unwrap().iter() {
|
||||
if let Some(on_tick) = w.get::<Handler<TickEvent>>() {
|
||||
on_tick.call(&w, &TickEvent(tick))
|
||||
}
|
||||
w.event(&TickEvent(tick));
|
||||
}
|
||||
tick += 1;
|
||||
std::thread::sleep(std::time::Duration::from_millis(rate_dur));
|
||||
@@ -25,5 +24,3 @@ impl Extension for TickExtension {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
event!(TickEvent(pub u32));
|
||||
|
||||
@@ -10,6 +10,8 @@ use crate::{
|
||||
|
||||
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 {
|
||||
@@ -20,9 +22,7 @@ impl VelocityExtension {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VelocityExtension {
|
||||
fn apply_velocity_xy(ticks: u16, widget: &Arc<Widget>) {
|
||||
if let Some(velocity) = widget.get::<Velocity>() {
|
||||
if let Some(mut t) = widget.get::<Transform>() {
|
||||
@@ -62,5 +62,3 @@ impl Extension for VelocityExtension {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
component!(Velocity(pub i32, pub i32));
|
||||
|
||||
+57
-12
@@ -1,57 +1,102 @@
|
||||
//! 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::{Widget, WidgetLoad},
|
||||
widget::{StaticWidget, Widget, WidgetLoad},
|
||||
Screen,
|
||||
};
|
||||
|
||||
/// Represents a single element in the RSX tree.
|
||||
pub enum RsxElement {
|
||||
Element(
|
||||
/// 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::Element(f, dep, child) => {
|
||||
let w = if let Some(parent) = &parent {
|
||||
let w = screen.draw_box(f);
|
||||
parent.0.lock().unwrap().draw_child(&w);
|
||||
w
|
||||
} else {
|
||||
screen.draw_box(f)
|
||||
};
|
||||
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::Element(Box::new(load), dependencies, children));
|
||||
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);
|
||||
}
|
||||
|
||||
+113
-10
@@ -1,9 +1,40 @@
|
||||
//! **OSUI** – A Rust Terminal User Interface Library
|
||||
//!
|
||||
//! OSUI is a library for building interactive and customizable terminal user interfaces in Rust.
|
||||
//! It provides a component system, real-time keyboard input handling, and a `rsx!` macro
|
||||
//! for defining UI elements in a declarative way, however that is optional.
|
||||
//!
|
||||
//! ✅ **Features**
|
||||
//! - 🧱 RSX-like syntax with `rsx!` macro
|
||||
//! - 🖥️ Virtual screen abstraction
|
||||
//! - 🎹 Keyboard input handling
|
||||
//! - 🎯 Component-based design
|
||||
//! - ⚡ Real-time rendering
|
||||
//!
|
||||
//! 🚀 **Quick Example**
|
||||
//! ```rust
|
||||
//! use osui::prelude::*;
|
||||
//!
|
||||
//! fn main() -> std::io::Result<()> {
|
||||
//! let screen = Screen::new();
|
||||
//! rsx! {
|
||||
//! "👋 Hello, World!"
|
||||
//! }.draw(&screen);
|
||||
//! screen.run()
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ---
|
||||
//! 🧰 For full documentation, visit: [osui.netlify.app/docs](https://osui.netlify.app/docs)
|
||||
//!
|
||||
//! 🧪 Examples and demos: [github.com/osui-rs/osui/demos](https://github.com/osui-rs/osui/tree/master/src/demos)
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::{
|
||||
extensions::{Extension, Handler},
|
||||
render_scope::RenderScope,
|
||||
widget::{Element, Widget, WidgetLoad},
|
||||
widget::{BoxedElement, DynWidget, Element, StaticWidget, Widget, WidgetLoad},
|
||||
};
|
||||
|
||||
pub mod elements;
|
||||
@@ -22,18 +53,41 @@ pub mod prelude {
|
||||
widget::*, *,
|
||||
};
|
||||
|
||||
pub use crate::style::{Dimension::{Full, Content}, Position::{Center, End}};
|
||||
pub use crate::style::{
|
||||
Dimension::{Content, Full},
|
||||
Position::{Center, End},
|
||||
};
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
@@ -43,31 +97,55 @@ unsafe impl Send for RenderWrapperEvent {}
|
||||
unsafe impl Sync for RenderWrapperEvent {}
|
||||
|
||||
impl Screen {
|
||||
/// Creates a new screen instance wrapped in an `Arc`.
|
||||
pub fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
widgets: Mutex::new(Vec::new()),
|
||||
extensions: Mutex::new(Vec::new()),
|
||||
running: Mutex::new(true),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn draw<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(
|
||||
/// Draws a static element and returns its widget handle.
|
||||
pub fn draw<E: Element + 'static + Send + Sync>(self: &Arc<Self>, element: E) -> Arc<Widget> {
|
||||
let w = Arc::new(Widget::Static(StaticWidget::new(Box::new(element))));
|
||||
self.widgets.lock().unwrap().push(w.clone());
|
||||
w
|
||||
}
|
||||
|
||||
/// Draws a boxed element and returns its widget handle.
|
||||
pub fn draw_box(self: &Arc<Self>, element: BoxedElement) -> Arc<Widget> {
|
||||
let w = Arc::new(Widget::Static(StaticWidget::new(element)));
|
||||
self.widgets.lock().unwrap().push(w.clone());
|
||||
w
|
||||
}
|
||||
|
||||
/// Adds an existing widget to the screen.
|
||||
pub fn draw_widget(self: &Arc<Self>, widget: Arc<Widget>) {
|
||||
self.widgets.lock().unwrap().push(widget);
|
||||
}
|
||||
|
||||
/// Draws a dynamic element using a closure and returns its widget handle.
|
||||
pub fn draw_dyn<F: FnMut() -> WidgetLoad + 'static + Send + Sync>(
|
||||
self: &Arc<Self>,
|
||||
element: F,
|
||||
) -> Arc<Widget> {
|
||||
let w = Arc::new(Widget::new(Box::new(element)));
|
||||
let w = Arc::new(Widget::Dynamic(DynWidget::new(element)));
|
||||
self.widgets.lock().unwrap().push(w.clone());
|
||||
w
|
||||
}
|
||||
|
||||
pub fn draw_box(
|
||||
/// 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::new(Box::new(element)));
|
||||
let w = Arc::new(Widget::Dynamic(DynWidget::new(element)));
|
||||
self.widgets.lock().unwrap().push(w.clone());
|
||||
w
|
||||
}
|
||||
|
||||
/// Registers an extension with the screen.
|
||||
pub fn extension<E: Extension + Send + Sync + 'static>(self: &Arc<Self>, ext: E) {
|
||||
self.extensions
|
||||
.lock()
|
||||
@@ -75,6 +153,9 @@ impl Screen {
|
||||
.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());
|
||||
@@ -82,12 +163,17 @@ impl Screen {
|
||||
|
||||
utils::hide_cursor()?;
|
||||
|
||||
loop {
|
||||
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();
|
||||
@@ -95,7 +181,7 @@ impl Screen {
|
||||
|
||||
utils::clear()?;
|
||||
for elem in self.widgets.lock().unwrap().iter() {
|
||||
if let Some(NoRender) = elem.get() {
|
||||
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);
|
||||
}
|
||||
@@ -107,6 +193,10 @@ impl Screen {
|
||||
wrapper.call(elem, &RenderWrapperEvent(&mut scope));
|
||||
} else {
|
||||
scope.clear();
|
||||
|
||||
if let Some(style) = elem.get() {
|
||||
scope.set_style(style);
|
||||
}
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
@@ -115,18 +205,31 @@ impl Screen {
|
||||
ext.lock().unwrap().render_widget(&mut scope, elem);
|
||||
}
|
||||
|
||||
elem.0.lock().unwrap().render(&mut scope);
|
||||
elem.get_elem().render(&mut scope);
|
||||
|
||||
if let Some(t) = elem.get() {
|
||||
scope.set_transform(&t);
|
||||
}
|
||||
scope.draw();
|
||||
|
||||
elem.0.lock().unwrap().after_render(&mut scope);
|
||||
elem.get_elem().after_render(&mut scope);
|
||||
}
|
||||
|
||||
elem.auto_refresh();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Closes the loop and calls `on_close` in the extensions
|
||||
pub fn close(self: &Arc<Self>) {
|
||||
*self.running.lock().unwrap() = false;
|
||||
|
||||
utils::show_cursor().unwrap();
|
||||
|
||||
utils::clear().unwrap();
|
||||
|
||||
for ext in self.extensions.lock().unwrap().iter() {
|
||||
ext.lock().unwrap().on_close(self.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+149
-23
@@ -1,3 +1,24 @@
|
||||
/// Declares a struct that implements the `Event` trait.
|
||||
///
|
||||
/// This macro simplifies the creation of event types used within OSUI's reactive system.
|
||||
///
|
||||
/// # Variants
|
||||
///
|
||||
/// - `event!(Name)`
|
||||
/// Defines a unit struct named `Name`.
|
||||
///
|
||||
/// - `event!(Name { ... })`
|
||||
/// Defines a named struct with fields.
|
||||
///
|
||||
/// - `event!(Name (...))`
|
||||
/// Defines a tuple struct.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust
|
||||
/// event!(Clicked);
|
||||
/// event!(Resized { width: u32, height: u32 });
|
||||
/// event!(Moved(u32, u32));
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! event {
|
||||
($name:ident) => {
|
||||
@@ -36,6 +57,28 @@ macro_rules! event {
|
||||
};
|
||||
}
|
||||
|
||||
/// 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) => {
|
||||
@@ -86,35 +129,29 @@ macro_rules! component {
|
||||
};
|
||||
}
|
||||
|
||||
/// Macro to create an event handler closure that calls a method on `self`
|
||||
/// Creates an event handler closure that calls a method on `self`.
|
||||
///
|
||||
/// This macro automates the pattern of capturing `self` as a raw pointer,
|
||||
/// then passing an event to a method on `self` inside an unsafe closure.
|
||||
/// Useful when you need to register `'static` event handlers that interact with the current instance.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `$self_ty`: The self type.
|
||||
/// - `$self`: The instance variable (usually `self`) to call the method on.
|
||||
/// - `$events`: The event source which has an `.on` method to register the handler.
|
||||
/// - `$method`: The method name on `self` to call when an event occurs.
|
||||
/// # 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.
|
||||
///
|
||||
/// # Usage
|
||||
/// # Example
|
||||
/// ```rust
|
||||
/// event_handler!(self, events, on_keypress);
|
||||
/// event_handler!(Self, self, events, on_event);
|
||||
/// ```
|
||||
///
|
||||
/// This expands roughly to:
|
||||
/// Expands roughly to:
|
||||
/// ```rust
|
||||
/// let self_ref = self as *mut Self;
|
||||
/// events.on(move |event| unsafe { (*self_ref).on_keypress(event) });
|
||||
/// events.on(move |es, e| unsafe { (*self_ref).on_event(es, e) });
|
||||
/// ```
|
||||
///
|
||||
/// # Safety
|
||||
/// This macro uses `unsafe` code because it dereferences a raw pointer inside the closure.
|
||||
/// Ensure that the `self` reference lives at least as long as the closure to avoid undefined behavior.
|
||||
///
|
||||
/// # Why use raw pointers here?
|
||||
/// Often, event handlers require `'static` closures, but `self` is a stack reference.
|
||||
/// Capturing `self` directly is not possible, so this workaround uses a raw pointer.
|
||||
/// 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) => {{
|
||||
@@ -123,6 +160,26 @@ macro_rules! event_handler {
|
||||
}};
|
||||
}
|
||||
|
||||
/// 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),* $(,)?) => {{
|
||||
@@ -132,6 +189,22 @@ macro_rules! transform {
|
||||
}};
|
||||
}
|
||||
|
||||
/// 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)*) => {{
|
||||
@@ -143,23 +216,76 @@ macro_rules! rsx {
|
||||
}};
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $s:literal $($rest:tt)*) => {
|
||||
// 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)* };
|
||||
};
|
||||
|
||||
($r:expr, $(%$dep:ident)* $(@$comp:expr;)* $name:path { $($inner:tt)* } ($($e:expr),*) $($rest:tt)*) => {
|
||||
// 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(<$name>::new($($e),*)) $(.component($comp))*
|
||||
$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, $(%$dep:ident)* $(@$comp:expr;)* $name:path { $($inner:tt)* } $($rest:tt)*) => {
|
||||
($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)* });
|
||||
|
||||
+3
-20
@@ -1,28 +1,11 @@
|
||||
mod demos;
|
||||
use osui::prelude::*;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
let screen = Screen::new();
|
||||
screen.extension(InputExtension);
|
||||
|
||||
app().draw(&screen);
|
||||
demos::app(screen.clone()).draw(&screen);
|
||||
|
||||
screen.run()
|
||||
}
|
||||
|
||||
fn app() -> Rsx {
|
||||
rsx! {
|
||||
@transform! {
|
||||
width: Full,
|
||||
height: Full,
|
||||
};
|
||||
Div {
|
||||
@transform! {
|
||||
width: Full,
|
||||
height: Full,
|
||||
};
|
||||
RoundedOutline {}
|
||||
|
||||
@Transform::center();
|
||||
"Welcome To OSUI!"
|
||||
} (0x000000)
|
||||
}
|
||||
}
|
||||
|
||||
+171
-25
@@ -1,81 +1,211 @@
|
||||
//! 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, Transform},
|
||||
style::{RawTransform, Style, Transform},
|
||||
utils::{self, hex_ansi_bg},
|
||||
};
|
||||
|
||||
/// Represents a single render instruction.
|
||||
#[derive(Clone)]
|
||||
enum RenderMethod {
|
||||
Text(String),
|
||||
TextColored(String, u32),
|
||||
Rectangle(u16, u16, u32),
|
||||
/// 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;
|
||||
}
|
||||
|
||||
pub fn draw_text(&mut self, text: &str) {
|
||||
self.render_stack.push(RenderMethod::Text(text.to_string()));
|
||||
/// 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);
|
||||
}
|
||||
|
||||
pub fn draw_text_colored(&mut self, text: &str, color: u32) {
|
||||
/// Adds a text draw instruction.
|
||||
pub fn draw_text_inverted(&mut self, x: u16, y: u16, text: &str) {
|
||||
self.render_stack
|
||||
.push(RenderMethod::TextColored(text.to_string(), color));
|
||||
.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);
|
||||
}
|
||||
|
||||
pub fn draw_rect(&mut self, width: u16, height: u16, color: u32) {
|
||||
/// 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::Rectangle(width, height, color));
|
||||
.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) {
|
||||
for m in &self.render_stack {
|
||||
match m {
|
||||
RenderMethod::Text(t) => {
|
||||
utils::print(self.transform.x, self.transform.y, t);
|
||||
}
|
||||
RenderMethod::TextColored(t, c) => utils::print(
|
||||
self.transform.x,
|
||||
self.transform.y,
|
||||
&(utils::hex_ansi(*c) + t),
|
||||
),
|
||||
RenderMethod::Rectangle(width, height, color) => {
|
||||
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)
|
||||
@@ -87,18 +217,19 @@ impl RenderScope {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears all render instructions and resets the internal state.
|
||||
pub fn clear(&mut self) {
|
||||
self.render_stack.clear();
|
||||
self.transform.width = 0;
|
||||
self.transform.height = 0;
|
||||
self.transform.x = 0;
|
||||
self.transform.y = 0;
|
||||
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 {
|
||||
@@ -114,6 +245,7 @@ impl RenderScope {
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns size, falling back to parent size if unset.
|
||||
pub fn get_size_or_parent(&self) -> (u16, u16) {
|
||||
(
|
||||
if self.transform.width == 0 {
|
||||
@@ -129,22 +261,36 @@ impl RenderScope {
|
||||
)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
+8
-5
@@ -4,6 +4,14 @@ use std::{
|
||||
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>>>,
|
||||
@@ -90,8 +98,3 @@ impl<T> DerefMut for Inner<T> {
|
||||
&mut self.value
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DependencyHandler: std::fmt::Debug + Send + Sync {
|
||||
fn add(&self);
|
||||
fn check(&self) -> bool;
|
||||
}
|
||||
|
||||
@@ -1,86 +1,156 @@
|
||||
//! 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);
|
||||
@@ -90,17 +160,21 @@ impl Transform {
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -111,6 +185,7 @@ impl Dimension {
|
||||
}
|
||||
|
||||
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 => {
|
||||
|
||||
+281
-59
@@ -1,39 +1,294 @@
|
||||
//! 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},
|
||||
sync::{Arc, Mutex, MutexGuard},
|
||||
};
|
||||
|
||||
use crate::{render_scope::RenderScope, state::DependencyHandler};
|
||||
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(&self, element: &Arc<Widget>) {}
|
||||
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;
|
||||
}
|
||||
|
||||
pub struct Widget(
|
||||
pub Mutex<BoxedElement>,
|
||||
/// 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(
|
||||
@@ -45,32 +300,26 @@ impl Widget {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn inject<F: FnMut(WidgetLoad) -> WidgetLoad + 'static + Send + Sync>(
|
||||
self: &Arc<Self>,
|
||||
f: F,
|
||||
) {
|
||||
{
|
||||
*self.4.lock().unwrap() = Some(Box::new(f));
|
||||
}
|
||||
/// 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();
|
||||
}
|
||||
|
||||
pub fn refresh(self: &Arc<Self>) {
|
||||
let w = (self.2.lock().unwrap())();
|
||||
match &mut *self.4.lock().unwrap() {
|
||||
Some(inject) => {
|
||||
let w = inject(w);
|
||||
*self.0.lock().unwrap() = w.0;
|
||||
*self.1.lock().unwrap() = w.1;
|
||||
}
|
||||
None => {
|
||||
*self.0.lock().unwrap() = w.0;
|
||||
*self.1.lock().unwrap() = w.1;
|
||||
}
|
||||
/// 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;
|
||||
}
|
||||
|
||||
pub fn auto_refresh(self: &Arc<Self>) {
|
||||
/// 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();
|
||||
@@ -78,30 +327,28 @@ impl Widget {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dependency<D: DependencyHandler + 'static>(self: &Arc<Self>, d: D) -> &Arc<Self> {
|
||||
/// 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));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dependency_box(self: &Arc<Self>, d: Box<dyn DependencyHandler>) -> &Arc<Self> {
|
||||
/// Adds a boxed dependency.
|
||||
pub fn dependency_box(&self, d: Box<dyn DependencyHandler>) {
|
||||
d.add();
|
||||
self.3.lock().unwrap().push(d);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
|
||||
pub fn component<C: Component + 'static>(&self, c: C) {
|
||||
self.1
|
||||
.lock()
|
||||
.unwrap()
|
||||
.entry(c.type_id())
|
||||
.or_insert_with(|| Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_component<C: Component + 'static>(self: &Arc<Self>, c: C) -> &Arc<Self> {
|
||||
pub fn set_component<C: Component + 'static>(&self, c: C) {
|
||||
self.1.lock().unwrap().insert(c.type_id(), Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
||||
@@ -110,31 +357,6 @@ impl Widget {
|
||||
.unwrap()
|
||||
.get(&TypeId::of::<C>())
|
||||
.and_then(|c| c.as_any().downcast_ref::<C>())
|
||||
.map(|c| c.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WidgetLoad(BoxedElement, HashMap<TypeId, BoxedComponent>);
|
||||
|
||||
impl WidgetLoad {
|
||||
pub fn new<E: Element + 'static>(e: E) -> Self {
|
||||
Self(Box::new(e), HashMap::new())
|
||||
}
|
||||
|
||||
pub fn component<C: Component + 'static>(mut self, c: C) -> Self {
|
||||
self.1.entry(c.type_id()).or_insert_with(|| Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_component<C: Component + 'static>(mut self, c: C) -> Self {
|
||||
self.1.insert(c.type_id(), Box::new(c));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get<C: Component + 'static + Clone>(&self) -> Option<C> {
|
||||
self.1
|
||||
.get(&TypeId::of::<C>())
|
||||
.and_then(|c| c.as_any().downcast_ref::<C>())
|
||||
.map(|c| c.clone())
|
||||
.map(Clone::clone)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user