commands and get_element_by_id

This commit is contained in:
2024-11-22 09:33:02 +01:00
parent 10c8f6d0ca
commit cc0ea4a9f5
6 changed files with 123 additions and 77 deletions
+1 -1
View File
@@ -22,6 +22,6 @@ crossterm = "0.28.1"
regex = "1.11.1" regex = "1.11.1"
lazy_static = "1.4" lazy_static = "1.4"
paste = "1.0.15" paste = "1.0.15"
osui-element = "0.1.5" osui-element = "0.1.8"
dyn-clone = "1.0.17" dyn-clone = "1.0.17"
flume = "=0.10.12" flume = "=0.10.12"
+7 -27
View File
@@ -4,44 +4,24 @@
#include <pthread.h> #include <pthread.h>
#include <time.h> #include <time.h>
typedef struct { extern boolean_t render_loop(void* args);
void* element; extern void *event_loop(void* args);
void* sender; extern void *cmd_loop(void* args);
void* receiver;
boolean_t running;
} LArgs;
extern boolean_t render(void* element); boolean_t c_run(void* args)
extern void *event_loop(void* element);
extern void *cmd_loop(void* element);
void sleep_ms(long milliseconds)
{
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, NULL);
}
boolean_t c_run(void* element, void* sender, void* receiver)
{ {
pthread_t event_thread; pthread_t event_thread;
pthread_t cmd_thread; pthread_t cmd_thread;
LArgs args = { .element = element, .sender = sender, .receiver = receiver, .running = 1 };
if (pthread_create(&event_thread, NULL, event_loop, &args) != 0) if (pthread_create(&event_thread, NULL, event_loop, args) != 0)
{ {
perror("Failed to create thread"); perror("Failed to create thread");
} }
if (pthread_create(&cmd_thread, NULL, cmd_loop, &args) != 0) if (pthread_create(&cmd_thread, NULL, cmd_loop, args) != 0)
{ {
perror("Failed to create thread"); perror("Failed to create thread");
} }
while (render(element) && args.running) return render_loop(args);
{
sleep_ms(20);
}
return 0;
} }
+56 -31
View File
@@ -9,22 +9,28 @@ use crate::utils::{
}; };
use std::{ffi::c_void, ptr::null, sync::mpsc}; use std::{ffi::c_void, ptr::null, sync::mpsc};
pub struct LArgs { pub struct LArgs<'a> {
pub element: *mut c_void, pub element: &'a mut Element,
pub sender: *const c_void,
pub receiver: *const c_void, // for sending commands
pub stx: mpsc::Sender<Command>,
pub srx: mpsc::Receiver<Command>,
// for returning command output
pub rtx: mpsc::Sender<Option<*mut Element>>,
pub rrx: mpsc::Receiver<Option<*mut Element>>,
pub running: bool, pub running: bool,
} }
extern "C" { extern "C" {
fn c_run(element: *mut c_void, sender: *const c_void, receiver: *const c_void) -> bool; fn c_run(args: *mut c_void) -> bool;
} }
fn event(element: &mut Element, event: Event) { fn event(element: &mut Element, event: Event, document: &Document) {
if let crossterm::event::Event::Resize(width, height) = event { if let crossterm::event::Event::Resize(width, height) = event {
element.update_data(width as usize, height as usize); element.update_data(width as usize, height as usize);
} }
element.event(event); element.event(event, document);
} }
pub fn run(element: &mut Element) -> bool { pub fn run(element: &mut Element) -> bool {
@@ -32,12 +38,16 @@ pub fn run(element: &mut Element) -> bool {
enable_raw_mode().unwrap(); enable_raw_mode().unwrap();
clear(); clear();
unsafe { unsafe {
let (tx, rx) = mpsc::channel::<Command>(); let (stx, srx) = mpsc::channel();
let c = c_run( let (rtx, rrx) = mpsc::channel();
element as *mut Element as *mut c_void, let c = c_run(&mut LArgs {
&tx as *const mpsc::Sender<Command> as *const c_void, running: true,
&rx as *const mpsc::Receiver<Command> as *const c_void, element,
); stx,
srx,
rtx,
rrx,
} as *mut LArgs as *mut c_void);
if !c { if !c {
show_cursor(); show_cursor();
disable_raw_mode().unwrap(); disable_raw_mode().unwrap();
@@ -48,18 +58,20 @@ pub fn run(element: &mut Element) -> bool {
} }
#[no_mangle] #[no_mangle]
extern "C" fn render(ptr: *mut c_void) -> bool { extern "C" fn render_loop(ptr: *mut c_void) -> bool {
if ptr.is_null() { if ptr.is_null() {
return false; return false;
} }
let element = unsafe { &mut *(ptr as *mut Element) }; let args = unsafe { &mut *(ptr as *mut LArgs) };
let (width, height) = get_term_size(); while args.running {
let mut frame: Vec<String> = create_frame(width, height); let (width, height) = get_term_size();
render_to_frame(true, width, &mut frame, element); let mut frame: Vec<String> = create_frame(width, height);
clear(); render_to_frame(true, width, &mut frame, args.element);
print!("{}", frame.join("")); clear();
flush(); print!("{}", frame.join(""));
true flush();
}
false
} }
#[no_mangle] #[no_mangle]
@@ -68,19 +80,24 @@ extern "C" fn event_loop(ptr: *mut c_void) -> *const c_void {
return null() as *const c_void; return null() as *const c_void;
} }
let args = unsafe { &mut *(ptr as *mut LArgs) }; let args = unsafe { &mut *(ptr as *mut LArgs) };
let element = unsafe { &mut *(args.element as *mut Element) }; let document = Document {
let tx = unsafe { &*(args.sender as *const mpsc::Sender<Command>) }; cmd_sender: args.stx.clone(),
cmd_recv: &args.rrx as *const mpsc::Receiver<Option<*mut Element>> as *const c_void,
};
let (width, height) = get_term_size(); let (width, height) = get_term_size();
element.update_data(width, height); args.element.update_data(width, height);
event(element, crossterm::event::Event::FocusGained); event(
args.element,
crossterm::event::Event::FocusGained,
&document,
);
while args.running { while args.running {
if ptr.is_null() { if ptr.is_null() {
break; break;
} }
event(element, crossterm::event::read().unwrap()); event(args.element, crossterm::event::read().unwrap(), &document);
tx.send(Command::Exit).unwrap();
} }
null() as *const c_void null() as *const c_void
} }
@@ -91,14 +108,22 @@ extern "C" fn cmd_loop(ptr: *mut c_void) -> *const c_void {
return null() as *const c_void; return null() as *const c_void;
} }
let args = unsafe { &mut *(ptr as *mut LArgs) }; let args = unsafe { &mut *(ptr as *mut LArgs) };
let _element = unsafe { &mut *(args.element as *mut Element) };
let rx = unsafe { &*(args.receiver as *const mpsc::Receiver<Command>) };
loop { loop {
match rx.recv().unwrap() { match args.srx.recv().unwrap() {
Command::Exit => { Command::Exit => {
args.running = false; args.running = false;
break; break;
} }
Command::GetElementById(id) => {
args.rtx
.send(if let Some(e) = args.element.get_element_by_id(&id) {
Some(e as *mut Element)
} else {
None
})
.unwrap();
}
} }
} }
null() null()
+39 -7
View File
@@ -43,7 +43,7 @@ pub use app::run;
pub mod prelude { pub mod prelude {
pub use crate::ui::Color::*; pub use crate::ui::Color::*;
pub use crate::{self as osui, css, rsx, rsx_elem, ui::*, Handler}; pub use crate::{self as osui, css, rsx, rsx_elem, ui::*, Handler};
pub use crate::{style, Command, Element, Value, Document}; pub use crate::{style, Command, Document, Element, Value};
// useful for Element making // useful for Element making
pub use crate::{run_handler, Children, ElementCore, ElementWidget}; pub use crate::{run_handler, Children, ElementCore, ElementWidget};
pub use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind}; pub use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind};
@@ -101,8 +101,8 @@ pub trait ElementWidget: ElementCore + std::fmt::Debug {
String::new() String::new()
} }
fn event(&mut self, event: Event) { fn event(&mut self, event: Event, document: &Document) {
_ = event _ = (event, document)
} }
} }
@@ -112,12 +112,12 @@ pub type Element = Box<dyn ElementWidget>;
/// Handler Struct /// Handler Struct
////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////
pub struct Handler<T>(pub Arc<Mutex<dyn FnMut(&mut T, Event) + Send + Sync>>); pub struct Handler<T>(pub Arc<Mutex<dyn FnMut(&mut T, Event, &Document) + Send + Sync>>);
impl<T> Handler<T> { impl<T> Handler<T> {
pub fn new<F>(handler_fn: F) -> Handler<T> pub fn new<F>(handler_fn: F) -> Handler<T>
where where
F: FnMut(&mut T, Event) + 'static + Send + Sync, F: FnMut(&mut T, Event, &Document) + 'static + Send + Sync,
{ {
Handler(Arc::new(Mutex::new(handler_fn))) Handler(Arc::new(Mutex::new(handler_fn)))
} }
@@ -125,7 +125,7 @@ impl<T> Handler<T> {
impl<T> Default for Handler<T> { impl<T> Default for Handler<T> {
fn default() -> Self { fn default() -> Self {
Handler(Arc::new(Mutex::new(|_: &mut T, _: Event| {}))) Handler(Arc::new(Mutex::new(|_: &mut T, _: Event, _: &Document| {})))
} }
} }
@@ -189,6 +189,24 @@ impl Children {
_ => None, _ => None,
} }
} }
pub fn set_text(&mut self, text: &str) {
match self {
Children::Text(t) => {
*t = text.to_string();
}
_ => {}
}
}
pub fn set_text_force(&mut self, text: &str) {
match self {
Children::Text(t) => {
*t = text.to_string();
}
_ => {
*self = Children::Text(text.to_string());
}
}
}
} }
/// Converts a `Element` into the struct /// Converts a `Element` into the struct
@@ -198,14 +216,28 @@ pub fn convert<T>(widget: &mut Box<dyn ElementWidget>) -> &mut Box<T> {
pub enum Command { pub enum Command {
Exit, Exit,
GetElementById(String),
} }
pub struct Document { pub struct Document {
cmd_sender: std::sync::mpsc::Sender<Command>, cmd_sender: std::sync::mpsc::Sender<Command>,
cmd_recv: *const std::ffi::c_void,
} }
impl Document { impl Document {
pub fn exit(&self) { pub fn exit(&self) {
self.cmd_sender.send(Command::Exit).unwrap(); self.cmd_sender.send(Command::Exit).unwrap();
} }
} pub fn get_element_by_id<T>(&self, id: &str) -> Option<&mut Box<T>> {
self.cmd_sender
.send(Command::GetElementById(id.to_string()))
.unwrap();
let rx =
unsafe { &*(self.cmd_recv as *const std::sync::mpsc::Receiver<Option<*mut Element>>) };
if let Ok(Some(e)) = rx.recv() {
Some(convert(unsafe { &mut *e }))
} else {
None
}
}
}
+11 -4
View File
@@ -1,17 +1,21 @@
// use std::sync::Arc;
use osui::prelude::*; use osui::prelude::*;
pub struct App {} pub struct App {}
fn main() { fn main() {
// let something = Arc::new(App {});
while osui::run(&mut app()) {} while osui::run(&mut app()) {}
} }
fn app() -> Element { fn app() -> Element {
rsx! { styling: Some(styles()), rsx! { styling: Some(styles()),
button { class: "btn", "Hello, World!" } button { class: "btn", on_click: Handler::new(|_, _, document| {
if let Some(txt) = document.get_element_by_id::<Text>("txt") {
txt.children.set_text("edited");
}
}), "Hello, World!" }
text { id: "txt", "Some text!" }
} }
} }
@@ -20,5 +24,8 @@ fn styles() -> Css {
.btn: clicked { .btn: clicked {
color: Blue color: Blue
} }
.btn: hover {
color: Red
}
} }
} }
+9 -7
View File
@@ -83,9 +83,11 @@ impl ElementWidget for Div<'_> {
frame.join("\n") frame.join("\n")
} }
fn event(&mut self, event: Event) { fn event(&mut self, event: Event, document: &Document) {
if let Some(styling) = self.styling.clone() { if event == Event::FocusGained {
self.set_styling(&styling); if let Some(styling) = self.styling.clone() {
self.set_styling(&styling);
}
} }
match event { match event {
Event::Key(key) => { Event::Key(key) => {
@@ -117,7 +119,7 @@ impl ElementWidget for Div<'_> {
_ => { _ => {
if let Some(c) = children.get_mut(*child) { if let Some(c) = children.get_mut(*child) {
c.event(event); c.event(event, document);
} }
*child *child
} }
@@ -126,7 +128,7 @@ impl ElementWidget for Div<'_> {
} }
_ => { _ => {
if let Some(child) = self.get_child() { if let Some(child) = self.get_child() {
child.event(event); child.event(event, document);
} }
} }
} }
@@ -153,12 +155,12 @@ impl ElementWidget for Button<'_> {
} }
} }
fn event(&mut self, event: Event) { fn event(&mut self, event: Event, document: &Document) {
match event { match event {
Event::Key(key) => { Event::Key(key) => {
if key.code == KeyCode::Enter { if key.code == KeyCode::Enter {
self.state = "clicked"; self.state = "clicked";
run_handler!(self.on_click(event)); run_handler!(self.on_click(event, document));
sleep(100); sleep(100);
self.state = ""; self.state = "";
} }