index : nmrs-tui
A fast, Vim-friendly NetworkManager TUI built in Rust.
about summary refs log tree commit diff
nmrs-tui / src / tui.rs
-rw-r--r-- blob 49aa50ab227a8ea66d99222729ded08679687812 2034 bytes (plain)
1
use anyhow::Result;
2
use crossterm::{
3
    ExecutableCommand,
4
    event::{self, Event, KeyCode},
5
    terminal::{self, disable_raw_mode, enable_raw_mode},
6
};
7
use ratatui::{
8
    Terminal,
9
    backend::CrosstermBackend,
10
    layout::{Constraint, Direction, Layout},
11
};
12
use std::io::stdout;
13
14
use crate::{app::App, ui::table};
15
16
pub struct Tui {
17
    terminal: Terminal<CrosstermBackend<std::io::Stdout>>,
18
}
19
20
impl Tui {
21
    pub fn new() -> anyhow::Result<Self> {
22
        let mut stdout = stdout();
23
        enable_raw_mode()?;
24
        stdout
25
            .execute(terminal::EnterAlternateScreen)?
26
            .execute(terminal::Clear(terminal::ClearType::All))?;
27
28
        let backend = CrosstermBackend::new(stdout);
29
        let terminal = Terminal::new(backend)?;
30
31
        Ok(Tui { terminal })
32
    }
33
    pub async fn run(&mut self, app: &mut App) -> Result<()> {
34
        while !app.should_quit {
35
            self.terminal.draw(|f| {
36
                let size = f.area();
37
                f.render_widget(
38
                    ratatui::widgets::Paragraph::new("netrs — NetworkManager TUI"),
39
                    size,
40
                );
41
                let layout = Layout::new(
42
                    Direction::Vertical,
43
                    [
44
                        Constraint::Percentage(50),
45
                        Constraint::Percentage(30),
46
                        Constraint::Percentage(20),
47
                    ],
48
                )
49
                .split(size);
50
                table::draw(f, layout[0], app);
51
            })?;
52
53
            if event::poll(std::time::Duration::from_millis(200))? {
54
                if let Event::Key(key) = event::read()? {
55
                    match key.code {
56
                        KeyCode::Char('q') => app.quit(),
57
                        _ => {}
58
                    }
59
                }
60
            }
61
        }
62
63
        disable_raw_mode()?;
64
        self.terminal
65
            .backend_mut()
66
            .execute(terminal::LeaveAlternateScreen)?;
67
        self.terminal.show_cursor()?;
68
        Ok(())
69
    }
70
}