首页 > 其他分享 >0057-Tui-进度条示例

0057-Tui-进度条示例

时间:2022-09-30 20:56:05浏览次数:77  
标签:layout render 示例 default app 0057 Tui gauge frame

环境

  • Time 2022-08-11
  • Rust 1.62.0
  • Tui 0.18.0

前言

说明

参考:https://github.com/fdehau/tui-rs/blob/master/examples/gauge.rs

目标

使用 tui-rs 显示进度条。

render_gauge1

fn render_gauge1<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条1").borders(Borders::ALL))
        .gauge_style(Style::default().fg(Color::Yellow))
        .percent(app.progress1);
    frame.render_widget(gauge, area);
}

render_gauge2

fn render_gauge2<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条2").borders(Borders::ALL))
        .gauge_style(Style::default().fg(Color::Magenta).bg(Color::Green))
        .percent(app.progress2)
        .label(format!("{}/100", app.progress2));
    frame.render_widget(gauge, area);
}

render_gauge3

fn render_gauge3<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let label = text::Span::styled(
        format!("{:.2}%", app.progress3 * 100.0),
        Style::default()
            .fg(Color::Red)
            .add_modifier(Modifier::ITALIC | Modifier::BOLD),
    );
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条3").borders(Borders::ALL))
        .gauge_style(Style::default().fg(Color::Yellow))
        .ratio(app.progress3)
        .label(label)
        .use_unicode(true);
    frame.render_widget(gauge, area);
}

render_gauge4

fn render_gauge4<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条4"))
        .gauge_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::ITALIC),
        )
        .percent(app.progress4)
        .label(format!("{}/100", app.progress2));
    frame.render_widget(gauge, area);
}

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::Percentage(25),
            layout::Constraint::Percentage(25),
            layout::Constraint::Percentage(25),
            layout::Constraint::Percentage(25),
        ])
        .split(frame.size());

    render_gauge1(frame, chunks[0], app);
    render_gauge2(frame, chunks[1], app);
    render_gauge3(frame, chunks[2], app);
    render_gauge4(frame, chunks[3], app);
}

效果展示

进度条

总结

使用 tui-rs 渲染进度条。

附录

源码

use anyhow::{Context, Result};
use crossterm::{event, terminal, ExecutableCommand};
use style::{Color, Modifier, Style};
use tui::backend::{Backend, CrosstermBackend};
use tui::{layout, style, text, widgets, Frame, Terminal};
use widgets::{Block, Borders};

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)?;
    terminal::disable_raw_mode()?;
    terminal
        .backend_mut()
        .execute(terminal::Clear(terminal::ClearType::All))?
        .execute(terminal::LeaveAlternateScreen)?
        .show_cursor()
        .context("重置控制台失败")
}

fn run<B: Backend>(terminal: &mut Terminal<B>) -> Result<()> {
    let timeout = std::time::Duration::from_millis(500);
    let mut app = App::new();
    loop {
        terminal.draw(|frame| ui(frame, &app))?;

        if event::poll(timeout)? {
            if let event::Event::Key(key) = event::read()? {
                use event::KeyCode::{Char, Esc};
                match key.code {
                    Char('q') | Char('Q') | Esc => return Ok(()),
                    _ => {}
                }
            }
        }
        app.on_tick();
    }
}
struct App {
    progress1: u16,
    progress2: u16,
    progress3: f64,
    progress4: u16,
}

impl App {
    fn new() -> App {
        App {
            progress1: 0,
            progress2: 0,
            progress3: 0.45,
            progress4: 0,
        }
    }

    fn on_tick(&mut self) {
        self.progress1 += 1;
        if self.progress1 > 100 {
            self.progress1 = 0;
        }
        self.progress2 += 2;
        if self.progress2 > 100 {
            self.progress2 = 0;
        }
        self.progress3 += 0.001;
        if self.progress3 > 1.0 {
            self.progress3 = 0.0;
        }
        self.progress4 += 1;
        if self.progress4 > 100 {
            self.progress4 = 0;
        }
    }
}

fn ui<B: Backend>(frame: &mut Frame<B>, app: &App) {
    let chunks = layout::Layout::default()
        .direction(layout::Direction::Vertical)
        .margin(2)
        .constraints([
            layout::Constraint::Percentage(25),
            layout::Constraint::Percentage(25),
            layout::Constraint::Percentage(25),
            layout::Constraint::Percentage(25),
        ])
        .split(frame.size());

    render_gauge1(frame, chunks[0], app);
    render_gauge2(frame, chunks[1], app);
    render_gauge3(frame, chunks[2], app);
    render_gauge4(frame, chunks[3], app);
}

fn render_gauge1<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条1").borders(Borders::ALL))
        .gauge_style(Style::default().fg(Color::Yellow))
        .percent(app.progress1);
    frame.render_widget(gauge, area);
}

fn render_gauge2<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条2").borders(Borders::ALL))
        .gauge_style(Style::default().fg(Color::Magenta).bg(Color::Green))
        .percent(app.progress2)
        .label(format!("{}/100", app.progress2));
    frame.render_widget(gauge, area);
}

fn render_gauge3<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let label = text::Span::styled(
        format!("{:.2}%", app.progress3 * 100.0),
        Style::default()
            .fg(Color::Red)
            .add_modifier(Modifier::ITALIC | Modifier::BOLD),
    );
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条3").borders(Borders::ALL))
        .gauge_style(Style::default().fg(Color::Yellow))
        .ratio(app.progress3)
        .label(label)
        .use_unicode(true);
    frame.render_widget(gauge, area);
}

fn render_gauge4<B: Backend>(frame: &mut Frame<B>, area: layout::Rect, app: &App) {
    let gauge = widgets::Gauge::default()
        .block(Block::default().title("进度条4"))
        .gauge_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::ITALIC),
        )
        .percent(app.progress4)
        .label(format!("{}/100", app.progress2));
    frame.render_widget(gauge, area);
}

标签:layout,render,示例,default,app,0057,Tui,gauge,frame
From: https://www.cnblogs.com/jiangbo4444/p/16746222.html

相关文章

  • 0049-Tui-创建控制台界面
    环境Time2022-08-08Rust1.62.0Tui0.18.0前言说明参考:https://docs.rs/tui/latest/tui/index.html目标使用tui-rs和crossterm启动一个控制台的终端界面。......
  • sanner格式以及示例
    格式:Scannerscanner=newScanner(System.in)“代码”Scanner.close(); 例:publicstaticvoidmain(String[]args){“”    //输入多个数字,并求其总和与平均......
  • Delphi XE MessageDialogAsync 和 MessageDialogSync [2] - 用法示例
    DelphiXEMessageDialogAsync和MessageDialogSync[2]-用法示例1、MessageDialogAsync//滔Roy2022.09.30usesFMX.Platform;//IFMXDialogServiceAsync......
  • C#使用CurrentUICulture切换语言
    C#使用CurrentUICulture切换语言-quanzhan-博客园(cnblogs.com)1、创建2个窗口   2、窗口1属性Localizable设置为True,Language选择英语(美国) 然后把窗口......
  • 秋色园QBlog技术原理解析:页面内容填充及多语言翻译流程演示示例(十)
    文章回顾:1:​​秋色园QBlog技术原理解析:开篇:整体认识(一)​​--介绍整体文件夹和文件的作用2:​​秋色园QBlog技术原理解析:认识整站处理流程(二)​​--介绍秋色园业务处理......
  • MarkDown 使用说明示例
    一、标题一级标题二级标题三级标题四级标题五级标题六级标题一级标题这是H2这是H3一级和二级标题还有一种写法就是下面加横杆,同时超过2个的=和-都可以有效果。This......
  • less写法示例
    less写法示例<divclass="parentDiv"><divclass="childDiv">childDiv1</div><divclass="childDiv">childDiv2</div><divclass="childDiv">childDiv3</div>......
  • Java Files.walk示例
    转自:https://blog.csdn.net/cyan20115/article/details/106548324Java8中提供了Files.walk API1.列出所有文件。try(Stream<Path>walk=Files.walk(Paths.get("C:......
  • 我学到了为 AWS 编写 Python TUI 控制台的五件事
    我学到了为AWS编写PythonTUI控制台的五件事AWSCloudExplorerrunningonLinux通常,我喜欢使用Terraform和Ansible使用声明性语言编写代码以部署基础设施。......
  • Delphi XE MessageDlg[2] TMsgDlgType、TMsgDlgBtn用法示例1
    DelphiXEMessageDlg[2]TMsgDlgType、TMsgDlgBtn用法示例11、TMsgDlgType //滔Roy2022.09.29MessageDlg('测试mtInformation.',TMsgDlgType.mtInformation,[TMs......