环境
- Time 2022-08-18
- Rust 1.63.0
- Tui 0.18.0
前言
说明
参考:https://github.com/fdehau/tui-rs/blob/master/examples/user_input.rs
目标
使用 tui-rs
来处理用户的输入。
Cargo.toml
[package]
edition = "2021"
name = "game"
version = "0.1.0"
[dependencies]
anyhow = "*"
crossterm = "*"
rand = "*"
tui = "*"
unicode-width = "*"
定义组件
use unicode_width::UnicodeWidthStr;
enum InputMode {
Normal,
Editing,
}
struct App {
input: String,
input_mode: InputMode,
messages: Vec<String>,
}
impl Default for App {
fn default() -> App {
App {
input: String::new(),
input_mode: InputMode::Normal,
messages: Vec::new(),
}
}
}
reset_terminal
fn reset_terminal() -> Result<()> {
terminal::disable_raw_mode()?;
std::io::stdout()
.execute(terminal::Clear(terminal::ClearType::All))?
.execute(terminal::LeaveAlternateScreen)?;
Ok(())
}
ui
fn ui<B: Backend>(frame: &mut Frame<B>, app: &App) {
let chunks = layout::Layout::default()
.direction(layout::Direction::Vertical)
.margin(2)
.constraints([
layout::Constraint::Length(1),
layout::Constraint::Length(3),
layout::Constraint::Min(1),
])
.split(frame.size());
let (msg, style) = match app.input_mode {
InputMode::Normal => (
vec![
Span::raw("Press "),
Span::styled("q", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to exit, "),
Span::styled("e", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to start editing."),
],
Style::default().add_modifier(Modifier::RAPID_BLINK),
),
InputMode::Editing => (
vec![
Span::raw("Press "),
Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to stop editing, "),
Span::styled("Enter", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to record the message"),
],
Style::default(),
),
};
let mut text = Text::from(Spans::from(msg));
text.patch_style(style);
let help_message = Paragraph::new(text);
frame.render_widget(help_message, chunks[0]);
let input = Paragraph::new(app.input.as_ref())
.style(match app.input_mode {
InputMode::Normal => Style::default(),
InputMode::Editing => Style::default().fg(Color::Yellow),
})
.block(Block::default().borders(Borders::ALL).title("Input"));
frame.render_widget(input, chunks[1]);
match app.input_mode {
InputMode::Normal =>
// Hide the cursor. `Frame` does this by default, so we don't need to do anything here
{}
InputMode::Editing => {
// Make the cursor visible and ask tui-rs to put it at the specified coordinates after rendering
frame.set_cursor(
// Put cursor past the end of the input text
chunks[1].x + app.input.width() as u16 + 1,
// Move one line down, from the border to the input line
chunks[1].y + 1,
)
}
}
let messages: Vec<ListItem> = app
.messages
.iter()
.enumerate()
.map(|(i, m)| {
let content = vec![Spans::from(Span::raw(format!("{}: {}", i, m)))];
ListItem::new(content)
})
.collect();
let messages =
List::new(messages).block(Block::default().borders(Borders::ALL).title("Messages"));
frame.render_widget(messages, chunks[2]);
}
效果展示
总结
使用 tui-rs
处理用户的输入,并且将输入的信息显示到终端。
附录
源码
use anyhow::Result;
use crossterm::{event, terminal, ExecutableCommand};
use tui::backend::{Backend, CrosstermBackend};
use tui::style::{Color, Modifier, Style};
use tui::text::{Span, Spans, Text};
use tui::widgets::{Block, Borders, List, ListItem, Paragraph};
use tui::{layout, Frame, Terminal};
pub fn main() -> Result<()> {
terminal::enable_raw_mode()?;
let mut backend = CrosstermBackend::new(std::io::stdout());
backend
.execute(terminal::EnterAlternateScreen)?
.execute(terminal::Clear(terminal::ClearType::All))?
.hide_cursor()?;
let mut terminal = tui::Terminal::new(backend)?;
run(&mut terminal)?;
reset_terminal()
}
fn reset_terminal() -> Result<()> {
terminal::disable_raw_mode()?;
std::io::stdout()
.execute(terminal::Clear(terminal::ClearType::All))?
.execute(terminal::LeaveAlternateScreen)?;
Ok(())
}
use unicode_width::UnicodeWidthStr;
enum InputMode {
Normal,
Editing,
}
struct App {
input: String,
input_mode: InputMode,
messages: Vec<String>,
}
impl Default for App {
fn default() -> App {
App {
input: String::new(),
input_mode: InputMode::Normal,
messages: Vec::new(),
}
}
}
fn run<B: Backend>(terminal: &mut Terminal<B>) -> Result<()> {
let timeout = std::time::Duration::from_millis(500);
let mut app = App::default();
loop {
terminal.draw(|frame| ui(frame, &app))?;
if event::poll(timeout)? {
if let event::Event::Key(key) = event::read()? {
use event::KeyCode::{Backspace, Char, Enter, Esc};
match app.input_mode {
InputMode::Normal => match key.code {
Char('e') => app.input_mode = InputMode::Editing,
Char('q') | Char('Q') | Esc => return Ok(()),
_ => {}
},
InputMode::Editing => match key.code {
Enter => app.messages.push(app.input.drain(..).collect()),
Char(c) => app.input.push(c),
Backspace => {
app.input.pop();
}
Esc => app.input_mode = InputMode::Normal,
_ => {}
},
}
}
}
}
}
fn ui<B: Backend>(frame: &mut Frame<B>, app: &App) {
let chunks = layout::Layout::default()
.direction(layout::Direction::Vertical)
.margin(2)
.constraints([
layout::Constraint::Length(1),
layout::Constraint::Length(3),
layout::Constraint::Min(1),
])
.split(frame.size());
let (msg, style) = match app.input_mode {
InputMode::Normal => (
vec![
Span::raw("Press "),
Span::styled("q", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to exit, "),
Span::styled("e", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to start editing."),
],
Style::default().add_modifier(Modifier::RAPID_BLINK),
),
InputMode::Editing => (
vec![
Span::raw("Press "),
Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to stop editing, "),
Span::styled("Enter", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to record the message"),
],
Style::default(),
),
};
let mut text = Text::from(Spans::from(msg));
text.patch_style(style);
let help_message = Paragraph::new(text);
frame.render_widget(help_message, chunks[0]);
let input = Paragraph::new(app.input.as_ref())
.style(match app.input_mode {
InputMode::Normal => Style::default(),
InputMode::Editing => Style::default().fg(Color::Yellow),
})
.block(Block::default().borders(Borders::ALL).title("Input"));
frame.render_widget(input, chunks[1]);
match app.input_mode {
InputMode::Normal =>
// Hide the cursor. `Frame` does this by default, so we don't need to do anything here
{}
InputMode::Editing => {
// Make the cursor visible and ask tui-rs to put it at the specified coordinates after rendering
frame.set_cursor(
// Put cursor past the end of the input text
chunks[1].x + app.input.width() as u16 + 1,
// Move one line down, from the border to the input line
chunks[1].y + 1,
)
}
}
let messages: Vec<ListItem> = app
.messages
.iter()
.enumerate()
.map(|(i, m)| {
let content = vec![Spans::from(Span::raw(format!("{}: {}", i, m)))];
ListItem::new(content)
})
.collect();
let messages =
List::new(messages).block(Block::default().borders(Borders::ALL).title("Messages"));
frame.render_widget(messages, chunks[2]);
}
标签:Span,default,app,terminal,Tui,InputMode,0068,input,输入
From: https://www.cnblogs.com/jiangbo4444/p/16746280.html