首页 > 其他分享 >0068-Tui-用户输入

0068-Tui-用户输入

时间:2022-09-30 21:22:27浏览次数:80  
标签:Span default app terminal Tui InputMode 0068 input 输入

环境

  • 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

相关文章

  • 0062-Tui-表格示例
    环境Time2022-08-16Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/table.rs目标使用tui-rs显示表格。定义应用......
  • 0063-Tui-页签示例
    环境Time2022-08-16Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/tabs.rs目标使用tui-rs显示页签。定义应用......
  • 0058-Tui-段落示例
    环境Time2022-08-12Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/paragraph.rs目标使用tui-rs显示段落。定义......
  • 0055-Tui-条形图示例
    环境Time2022-08-09Rust1.62.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/barchart.rs目标使用tui-rs显示条形图。第......
  • 0056-Tui-简单进度条
    环境Time2022-08-11Rust1.62.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/gauge.rs目标使用tui-rs显示进度条。定义数......
  • 0057-Tui-进度条示例
    环境Time2022-08-11Rust1.62.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/gauge.rs目标使用tui-rs显示进度条。render......
  • 0049-Tui-创建控制台界面
    环境Time2022-08-08Rust1.62.0Tui0.18.0前言说明参考:https://docs.rs/tui/latest/tui/index.html目标使用tui-rs和crossterm启动一个控制台的终端界面。......
  • java字符串输入然后语音输出
    1.将jacob.jar考到项目中进行构建路径。2.将jacob-1.17-M2-x32.dll或者jacob-1.17-M2-x64.dll,考到系统盘:\Windows\System32\下面。3.将jacob-1.17-M2-x32.dll或者jacob-......
  • h5页面在ios手机输入框内emoji表情长度判断
    1、需求:要写一个讨论区的h5页面,当然包含了输入框并且输入框限制字符数30个,测试发现在ios手机输入emoji表情后输入框内就会超出所限制的字符长度,(说白了就是只要输入表......
  • C#使用CurrentUICulture切换语言
    C#使用CurrentUICulture切换语言-quanzhan-博客园(cnblogs.com)1、创建2个窗口   2、窗口1属性Localizable设置为True,Language选择英语(美国) 然后把窗口......