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 c258375d211deb8e015599bc544d57c074ada17b 3556 bytes (plain)
1
use crossterm::{
2
    ExecutableCommand,
3
    event::{Event, EventStream},
4
    terminal::{self, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
5
};
6
7
use ratatui::{
8
    Frame, Terminal,
9
    backend::CrosstermBackend,
10
    layout::{Constraint, Layout},
11
};
12
use std::{io, time::Duration};
13
use tokio::time;
14
use tokio_stream::StreamExt;
15
16
use crate::{
17
    action::{Action, ActionHandler},
18
    app::{App, Focus},
19
    events,
20
    ui::{PanelKind, header, help, tabs::Tabs, toast},
21
};
22
23
pub struct Tui {
24
    pub terminal: Terminal<CrosstermBackend<io::Stdout>>,
25
}
26
27
impl Tui {
28
    pub fn new() -> anyhow::Result<Self> {
29
        let mut stdout = io::stdout();
30
        enable_raw_mode()?;
31
        stdout
32
            .execute(terminal::EnterAlternateScreen)?
33
            .execute(terminal::Clear(terminal::ClearType::All))?;
34
35
        let backend = CrosstermBackend::new(stdout);
36
        let terminal = Terminal::new(backend)?;
37
38
        Ok(Tui { terminal })
39
    }
40
41
    pub async fn run(&mut self, app: &mut App) -> anyhow::Result<()> {
42
        let mut reader = EventStream::new();
43
        let mut last_tick = time::Instant::now();
44
        let mut tick_interval = time::interval(Duration::from_millis(50));
45
46
        while !app.should_quit {
47
            self.terminal.draw(|f| {
48
                Self::draw(f, app);
49
            })?;
50
51
            tokio::select! {
52
                maybe_event = reader.next() => {
53
                    if let Some(Ok(Event::Key(key))) = maybe_event {
54
                        events::handle_events(app, key);
55
                        trace!("Event: {:?}!", key);
56
                    }
57
                }
58
59
                _ = tick_interval.tick() => {}
60
            }
61
62
            let now = time::Instant::now();
63
            let delta = now.saturating_duration_since(last_tick);
64
            last_tick = now;
65
            app.action.send(Action::Tick(delta));
66
67
            ActionHandler::handle_actions(app).await?;
68
        }
69
70
        Ok(())
71
    }
72
73
    fn draw(f: &mut Frame, app: &mut App) {
74
        let size = f.area();
75
        let layout = &app.config.ui.layout;
76
77
        let (panel_kinds, constraints): (Vec<PanelKind>, Vec<Constraint>) =
78
            layout.panels.iter().map(|p| (p.kind, p.constraint)).unzip();
79
        let chunks = Layout::new(layout.direction, constraints).split(size);
80
81
        for (kind, area) in panel_kinds.into_iter().zip(chunks.iter()) {
82
            match kind {
83
                PanelKind::Header => header::draw(f, *area, app),
84
                PanelKind::KnownNetworks => Tabs::KnownNetworks.draw(f, *area, app),
85
                PanelKind::AvailableNetworks => Tabs::AvailableNetworks.draw(f, *area, app),
86
                PanelKind::Devices => Tabs::Devices.draw(f, *area, app),
87
                PanelKind::Help => help::draw(f, *area, &app.focus),
88
            }
89
        }
90
91
        if let Focus::Popup(popup) = &app.focus {
92
            popup.draw(f, &app.config.ui);
93
        }
94
95
        toast::draw(f, &app.config.ui.toast, &app.toasts);
96
    }
97
98
    pub fn restore_terminal(terminal: Option<&mut CrosstermBackend<io::Stdout>>) {
99
        let _ = disable_raw_mode();
100
        if let Some(terminal) = terminal {
101
            let _ = terminal.execute(LeaveAlternateScreen);
102
            let _ = terminal.execute(crossterm::cursor::Show);
103
        } else {
104
            let _ = io::stdout().execute(LeaveAlternateScreen);
105
            let _ = io::stdout().execute(crossterm::cursor::Show);
106
        };
107
    }
108
}
109
110
impl Drop for Tui {
111
    fn drop(&mut self) {
112
        Self::restore_terminal(Some(self.terminal.backend_mut()));
113
    }
114
}