use crate::*; //use unicode_width::{UnicodeWidthStr, UnicodeWidthChar}; //use rand::distributions::uniform::UniformSampler; pub(crate) use ::{ std::{ io::{stdout, Write}, time::Duration, }, ratatui::{ prelude::{Style, Position, Backend, Color}, style::{Modifier}, backend::{CrosstermBackend, ClearType}, layout::{Size, Rect}, buffer::{Buffer, Cell}, crossterm::{ ExecutableCommand, terminal::{EnterAlternateScreen, LeaveAlternateScreen, enable_raw_mode, disable_raw_mode}, //event::{poll, read, Event, KeyEvent, KeyCode, KeyModifiers, KeyEventKind, KeyEventState}, } }, crossterm::event::read, }; mod border; pub use self::border::*; mod buffer; pub use self::buffer::*; mod event; pub use self::event::*; mod keys; pub use self::keys::*; mod modify; pub use self::modify::*; mod phat; pub use self::phat::*; mod repeat; pub use self::repeat::*; mod scroll; pub use self::scroll::*; #[macro_export] macro_rules! tui_app { ($Struct:ident { $($fields:tt)* }) => { #[dizzle::namespace(bool)] #[dizzle::namespace(u8)] #[dizzle::namespace(u16)] #[dizzle::namespace(Option)] #[dizzle::namespace(Color Tui::eval_color_expr)] #[derive(Debug, Default)] pub struct $Struct { $($fields)* } tui_main!($Struct { ..Default::default() }); } } /// Implement standard [main] entrypoint for TUI apps. #[macro_export] macro_rules! tui_main { ($state:expr) => { pub fn main () -> Usually<()> { tengri::Tui::setup_panic(); Exit::run(|exit|tengri::Tui::run_main( exit, ::std::sync::Arc::new(::std::sync::RwLock::new($state)) )) } } } /// Enable TUI output for state struct. #[macro_export] macro_rules! tui_view { ($self:ident: $State:ty $body:block) => { impl tengri::View for $State { fn view (&$self) -> impl tengri::Draw $body } } } /// Enable TUI keyboard input for main state struct. #[macro_export] macro_rules! tui_keys { ($self:ident:$State:ty,$input:ident $($body:tt)+) => { impl dizzle::Apply> for $State { fn apply (&mut $self, $input: &tengri::TuiEvent) -> Usually<()> $($body)+ } }; } /// Terminal output. pub enum Tui { /// Draw mode: updates contained [Buffer]. Draw ( /// Ratatui buffer; area is screen size Buffer, /// Current draw area XYWH ), /// Discard mode: only computes sizes Layout ( /// Draw area; no buffer XYWH ) } impl Screen for Tui { type Unit = u16; fn area (&self) -> XYWH { self.into() } fn size <'a> ( &mut self, area: impl Into>>, draw: impl Draw, ) -> Drawn { Self::Layout(self.area()).clip(area, &|to|draw.draw(to)) } fn draw <'a> ( &mut self, area: impl Into>>, draw: impl Draw ) -> Drawn { self.clip(area, &|to|draw.draw(to)) } fn clip ( &mut self, area: impl Into>>, draw: &impl Fn(&mut Self)->T, ) -> T { let prev = self.area(); if let Some(area) = area.into() { *self.area_mut() = area.into(); } let result = draw(self); *self.area_mut() = prev; result } } impl Tui { pub fn setup_panic () { use ::std::panic::{set_hook, PanicHookInfo}; use ::better_panic::{Settings, Verbosity}; let panic = Settings::auto() .verbosity(Verbosity::Full) .create_panic_handler(); set_hook(Box::new(move |info: &PanicHookInfo|{ let _ = Tui::teardown(&mut stdout()); panic(info); })); } pub fn run_main (exit: Exit, state: Arc>) -> Usually<()> where T: Draw + Apply> + Send + Sync + 'static { let scan = Duration::from_millis(100); let frame = Duration::from_millis(10); let (_input, output) = Tui::io(exit.as_ref(), &state, scan, frame, std::io::stdout())?; let _ = output.join(); Tui::teardown(&mut stdout()) } /// Spawn the TUI input and output threadsl. pub fn io < T: Draw + Apply> + Send + Sync + 'static, W: Write + Send + Sync + 'static, > ( exited: &Arc, state: &Arc>, poll: Duration, sleep: Duration, output: W, ) -> Result<(Task, Task), Box> { Ok(( Tui::input(exited, state, poll)?, Tui::output(exited, state, sleep, output)?, )) } /// Spawn the TUI input thread which reads keys from the terminal. pub fn input > + Send + Sync + 'static> ( exited: &Arc, state: &Arc>, poll: Duration ) -> Result { let exited = exited.clone(); let state = state.clone(); Task::new_poll(Some("tengri input"), exited.clone(), poll, move |_| { let event = read().unwrap(); if Exit::is(&event) { exited.store(true, Relaxed); } else if let Err(e) = state.write().apply(&TuiEvent(event)) { panic!("{e}") } }) } pub fn teardown (backend: &mut W) -> Usually<()> { use ::ratatui::backend::Backend; stdout().execute(LeaveAlternateScreen)?; CrosstermBackend::new(backend).show_cursor()?; disable_raw_mode().map_err(Into::into) } pub fn new (width: u16, height: u16) -> Self { Self::Draw(Buffer::empty(Rect { x: 0, y: 0, width, height }), XYWH(0, 0, width, height)) } pub fn resize (&mut self, back: &mut CrosstermBackend, width: u16, height: u16) { let size = Rect { x: 0, y: 0, width, height }; if let Self::Draw(buffer, ..) = self { if buffer.area != size { back.clear_region(ClearType::All).unwrap(); buffer.resize(size); buffer.reset(); } } } pub fn redraw <'b, W: Write> ( &'b mut self, back: &mut CrosstermBackend, next: &'b mut Self ) { if let Self::Draw(prev, ..) = self && let Self::Draw(next, ..) = next { let updates = prev.diff(&next); back.draw(updates.into_iter()).expect("failed to render"); Backend::flush(back).expect("failed to flush output new"); std::mem::swap(prev, next); next.reset(); } } pub fn update (&mut self, callback: &impl Fn(&mut Cell, u16, u16)) -> XYWH { let XYWH(x0, y0, w, h) = self.area(); if let Self::Draw(buffer, ..) = self { for row in 0..h { let y = y0 + row; for col in 0..w { let x = x0 + col; if x < buffer.area.width && y < buffer.area.height { if let Some(cell) = buffer.cell_mut(Position { x, y }) { callback(cell, col, row); } } } } } self.xywh() } pub fn blit (&mut self, text: &impl AsRef, x: u16, y: u16, style: Option