mirror of https://github.com/fdehau/tui-rs
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
2.1 KiB
Rust
78 lines
2.1 KiB
Rust
3 years ago
|
use crate::{app::App, ui};
|
||
5 years ago
|
use crossterm::{
|
||
3 years ago
|
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
|
||
5 years ago
|
execute,
|
||
|
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||
|
};
|
||
5 years ago
|
use std::{
|
||
5 years ago
|
error::Error,
|
||
3 years ago
|
io,
|
||
5 years ago
|
time::{Duration, Instant},
|
||
5 years ago
|
};
|
||
3 years ago
|
use tui::{
|
||
|
backend::{Backend, CrosstermBackend},
|
||
|
Terminal,
|
||
|
};
|
||
6 years ago
|
|
||
3 years ago
|
pub fn run(tick_rate: Duration, enhanced_graphics: bool) -> Result<(), Box<dyn Error>> {
|
||
3 years ago
|
// setup terminal
|
||
5 years ago
|
enable_raw_mode()?;
|
||
3 years ago
|
let mut stdout = io::stdout();
|
||
4 years ago
|
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
|
||
5 years ago
|
let backend = CrosstermBackend::new(stdout);
|
||
6 years ago
|
let mut terminal = Terminal::new(backend)?;
|
||
|
|
||
3 years ago
|
// create app and run it
|
||
3 years ago
|
let app = App::new("Crossterm Demo", enhanced_graphics);
|
||
3 years ago
|
let res = run_app(&mut terminal, app, tick_rate);
|
||
|
|
||
|
// restore terminal
|
||
|
disable_raw_mode()?;
|
||
|
execute!(
|
||
|
terminal.backend_mut(),
|
||
|
LeaveAlternateScreen,
|
||
|
DisableMouseCapture
|
||
|
)?;
|
||
|
terminal.show_cursor()?;
|
||
6 years ago
|
|
||
3 years ago
|
if let Err(err) = res {
|
||
|
println!("{:?}", err)
|
||
|
}
|
||
6 years ago
|
|
||
3 years ago
|
Ok(())
|
||
|
}
|
||
6 years ago
|
|
||
3 years ago
|
fn run_app<B: Backend>(
|
||
|
terminal: &mut Terminal<B>,
|
||
|
mut app: App,
|
||
|
tick_rate: Duration,
|
||
|
) -> io::Result<()> {
|
||
|
let mut last_tick = Instant::now();
|
||
6 years ago
|
loop {
|
||
4 years ago
|
terminal.draw(|f| ui::draw(f, &mut app))?;
|
||
3 years ago
|
|
||
|
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()? {
|
||
|
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(),
|
||
|
_ => {}
|
||
5 years ago
|
}
|
||
6 years ago
|
}
|
||
|
}
|
||
3 years ago
|
if last_tick.elapsed() >= tick_rate {
|
||
|
app.on_tick();
|
||
|
last_tick = Instant::now();
|
||
|
}
|
||
6 years ago
|
if app.should_quit {
|
||
3 years ago
|
return Ok(());
|
||
6 years ago
|
}
|
||
|
}
|
||
|
}
|