mirror of
https://github.com/ratatui-org/ratatui
synced 2024-11-25 22:20:31 +00:00
f7af8a3863
Order imports by std, external, crate and group them by crate
81 lines
2.2 KiB
Rust
81 lines
2.2 KiB
Rust
use std::{
|
|
error::Error,
|
|
io,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use crossterm::{
|
|
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
|
|
execute,
|
|
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
|
};
|
|
use ratatui::{
|
|
backend::{Backend, CrosstermBackend},
|
|
Terminal,
|
|
};
|
|
|
|
use crate::{app::App, ui};
|
|
|
|
pub fn run(tick_rate: Duration, enhanced_graphics: bool) -> Result<(), Box<dyn Error>> {
|
|
// setup terminal
|
|
enable_raw_mode()?;
|
|
let mut stdout = io::stdout();
|
|
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
|
|
let backend = CrosstermBackend::new(stdout);
|
|
let mut terminal = Terminal::new(backend)?;
|
|
|
|
// create app and run it
|
|
let app = App::new("Crossterm Demo", enhanced_graphics);
|
|
let res = run_app(&mut terminal, app, tick_rate);
|
|
|
|
// restore terminal
|
|
disable_raw_mode()?;
|
|
execute!(
|
|
terminal.backend_mut(),
|
|
LeaveAlternateScreen,
|
|
DisableMouseCapture
|
|
)?;
|
|
terminal.show_cursor()?;
|
|
|
|
if let Err(err) = res {
|
|
println!("{err:?}");
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn run_app<B: Backend>(
|
|
terminal: &mut Terminal<B>,
|
|
mut app: App,
|
|
tick_rate: Duration,
|
|
) -> io::Result<()> {
|
|
let mut last_tick = Instant::now();
|
|
loop {
|
|
terminal.draw(|f| ui::draw(f, &mut app))?;
|
|
|
|
let timeout = tick_rate
|
|
.checked_sub(last_tick.elapsed())
|
|
.unwrap_or_else(|| Duration::from_secs(0));
|
|
if crossterm::event::poll(timeout)? {
|
|
if let Event::Key(key) = event::read()? {
|
|
if key.kind == KeyEventKind::Press {
|
|
match key.code {
|
|
KeyCode::Char(c) => app.on_key(c),
|
|
KeyCode::Left => app.on_left(),
|
|
KeyCode::Up => app.on_up(),
|
|
KeyCode::Right => app.on_right(),
|
|
KeyCode::Down => app.on_down(),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if last_tick.elapsed() >= tick_rate {
|
|
app.on_tick();
|
|
last_tick = Instant::now();
|
|
}
|
|
if app.should_quit {
|
|
return Ok(());
|
|
}
|
|
}
|
|
}
|