环境
- Time 2022-08-23
- Rust 1.63.0
- Tui 0.19.0
前言
说明
参考:https://github.com/fdehau/tui-rs/tree/master/examples/demo
目标
实现 tui-rs
的综合示例程序,终端的开启和还原。
main.rs
mod crossterm;
use std::time::Duration;
use crate::crossterm::run;
use argh::FromArgs;
/// Tui 的示例程序
#[derive(Debug, FromArgs)]
struct Cli {
/// 刷新的间隔时间
#[argh(option, default = "250")]
tick_rate: u64,
/// 是否使用Unicode增强
#[argh(option, default = "true")]
enhanced_graphics: bool,
}
fn main() -> anyhow::Result<()> {
let cli: Cli = argh::from_env();
let tick_rate = Duration::from_millis(cli.tick_rate);
run(tick_rate, cli.enhanced_graphics)
}
run
pub fn run(tick_rate: Duration, enhanced_graphics: bool) -> Result<()> {
terminal::enable_raw_mode()?;
let mut backend = CrosstermBackend::new(std::io::stdout());
backend
.execute(terminal::EnterAlternateScreen)?
.execute(EnableMouseCapture)?
.execute(terminal::Clear(terminal::ClearType::All))?
.hide_cursor()?;
let mut terminal = tui::Terminal::new(backend)?;
let app = App::new("Tui 综合示例", enhanced_graphics);
let res = run_app(&mut terminal, app, tick_rate);
terminal::disable_raw_mode()?;
terminal
.backend_mut()
.execute(terminal::Clear(terminal::ClearType::All))?
.execute(terminal::LeaveAlternateScreen)?
.execute(DisableMouseCapture)?
.show_cursor()
.context("重置控制台失败")
}
run_app
fn run_app<B: Backend>(
terminal: &mut Terminal<B>,
mut app: App,
tick_rate: Duration,
) -> Result<()> {
let mut last_tick = std::time::Instant::now();
loop {
terminal.draw(|frame| ui::draw(frame, &mut app))?;
let timeout = tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or_default();
if event::poll(timeout)? {
if let event::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(),
_ => {}
}
}
}
if last_tick.elapsed() >= tick_rate {
app.on_tick();
last_tick = std::time::Instant::now();
}
if app.should_quit {
return Ok(());
}
}
}
总结
实现 tui-rs
的综合示例程序,终端的开启和还原。暂时不能运行,存在编译错误。