working render

This commit is contained in:
2024-11-20 15:47:27 +01:00
parent e55606b9cf
commit e4835b9efa
5 changed files with 62 additions and 95 deletions
+36 -31
View File
@@ -1,52 +1,55 @@
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use crossterm::{
event::Event,
terminal::{disable_raw_mode, enable_raw_mode},
};
use crate::{
utils::{clear, create_frame, flush, get_term_size, hide_cursor, render_to_frame, show_cursor},
Element, State, StateChanger,
Element, StateChanger,
};
use std::ffi::c_void;
use std::{ffi::c_void, ptr::null};
extern "C" {
fn c_run(element: *mut c_void) -> bool;
}
#[no_mangle]
pub extern "C" fn render(ptr: *mut c_void, state: u32) {
let element = unsafe {
assert!(!ptr.is_null(), "Pointer is null");
&mut *(ptr as *mut Element)
};
extern "C" fn render(ptr: *mut c_void) -> bool {
if ptr.is_null() {
return false;
}
let element = unsafe { &mut *(ptr as *mut Element) };
let (width, height) = get_term_size();
let mut frame: Vec<String> = create_frame(width, height);
render_to_frame(State::from_u32(state), width, &mut frame, element);
render_to_frame(true, width, &mut frame, element);
clear();
print!("{}", frame.join(""));
flush();
true
}
#[no_mangle]
pub extern "C" fn event(ptr: *mut c_void, state: *mut u32) {
let event = crossterm::event::read().unwrap();
let element = unsafe {
assert!(!ptr.is_null(), "Pointer is null");
&mut *(ptr as *mut Element)
};
extern "C" fn event_loop(ptr: *mut c_void) -> *const c_void {
if ptr.is_null() {
return null() as *const c_void;
}
let element = unsafe { &mut *(ptr as *mut Element) };
let (width, height) = get_term_size();
element.update_data(width, height);
loop {
if ptr.is_null() {
break;
}
event(element, crossterm::event::read().unwrap())
}
null() as *const c_void
}
fn event(element: &mut Element, event: Event) {
if let crossterm::event::Event::Resize(width, height) = event {
element.update_data(width as usize, height as usize);
}
element.event(event, &StateChanger(state));
}
#[no_mangle]
pub extern "C" fn init_event(ptr: *mut c_void, state: *mut u32) {
let event = crossterm::event::Event::FocusGained;
let element = unsafe {
assert!(!ptr.is_null(), "Pointer is null");
&mut *(ptr as *mut Element)
};
let (width, height) = get_term_size();
element.update_data(width, height);
element.event(event, &StateChanger(state));
element.event(event, &StateChanger(&mut 0));
}
pub fn run(element: &mut Element) -> bool {
@@ -55,9 +58,11 @@ pub fn run(element: &mut Element) -> bool {
clear();
unsafe {
let c = c_run(element as *mut Element as *mut c_void);
show_cursor();
disable_raw_mode().unwrap();
clear();
if !c {
show_cursor();
disable_raw_mode().unwrap();
clear();
}
return c;
}
}