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 da52566a91efab9c3dba7a70d04e4c3a610fe608 4332 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, ToastRequest},
18
    app::{App, Focus, Popups, Selected},
19
    events,
20
    ui::{
21
        PanelKind, help, popup, table,
22
        toast::{self, Urgency},
23
    },
24
};
25
26
pub struct Tui {
27
    pub terminal: Terminal<CrosstermBackend<io::Stdout>>,
28
}
29
30
impl Tui {
31
    pub fn new() -> anyhow::Result<Self> {
32
        let mut stdout = io::stdout();
33
        enable_raw_mode()?;
34
        stdout
35
            .execute(terminal::EnterAlternateScreen)?
36
            .execute(terminal::Clear(terminal::ClearType::All))?;
37
38
        let backend = CrosstermBackend::new(stdout);
39
        let terminal = Terminal::new(backend)?;
40
41
        Ok(Tui { terminal })
42
    }
43
44
    pub async fn run(&mut self, app: &mut App) -> anyhow::Result<()> {
45
        let mut reader = EventStream::new();
46
        let mut last_tick = time::Instant::now();
47
        let mut tick_interval = time::interval(Duration::from_millis(50));
48
49
        while !app.should_quit {
50
            self.terminal.draw(|f| {
51
                Self::draw(f, app);
52
            })?;
53
54
            tokio::select! {
55
                maybe_event = reader.next() => {
56
57
                    if let Some(Ok(Event::Key(key))) = maybe_event
58
                    {
59
                        events::handle_events(app, key).await?;
60
                        trace!("Event: {:?}!", key);
61
                    }
62
                }
63
64
                _ = tick_interval.tick() => {
65
66
                }
67
            }
68
69
            let now = time::Instant::now();
70
            let delta = now.saturating_duration_since(last_tick);
71
            last_tick = now;
72
            app.action.send(Action::Tick(delta));
73
74
            ActionHandler::handle_actions(app).await?;
75
        }
76
77
        Ok(())
78
    }
79
80
    fn draw(f: &mut Frame, app: &mut App) {
81
        let size = f.area();
82
        let layout = &app.config.ui.layout;
83
84
        let panel_kinds: Vec<PanelKind> =
85
            app.config.ui.layout.panels.iter().map(|p| p.kind).collect();
86
        let constraints: Vec<Constraint> = layout.panels.iter().map(|p| p.constraint).collect();
87
88
        let chunks = Layout::new(layout.direction, constraints).split(size);
89
90
        for (kind, area) in panel_kinds.iter().zip(chunks.iter()) {
91
            match kind {
92
                PanelKind::KnownNetworks => table::draw_known_network(f, *area, app),
93
                PanelKind::AvailableNetworks => table::draw_available_network(f, *area, app),
94
                PanelKind::Devices => table::draw_devices(f, *area, app),
95
                PanelKind::Help => help::draw(f, *area, app.focus),
96
            }
97
        }
98
99
        if let Focus::Popup(popup) = app.focus {
100
            match popup {
101
                Popups::Password => {
102
                    if let Some(Selected::Network(net)) = app.selected() {
103
                        popup::draw_auth(f, &app.input, net, &app.config.ui.password_popup)
104
                    } else {
105
                        app.action.send(Action::ShowToast(Box::new(ToastRequest {
106
                            title: None,
107
                            msg: "Can't find selected network".into(),
108
                            urgency: Urgency::Critical,
109
                            duration: None,
110
                        })));
111
                        app.action.send(Action::SetFocus(app.last_focus));
112
                    }
113
                }
114
            }
115
        }
116
117
        toast::draw(f, &app.config.ui.toast, &app.toasts);
118
    }
119
120
    pub fn restore_terminal(terminal: Option<&mut CrosstermBackend<io::Stdout>>) {
121
        let _ = disable_raw_mode();
122
        if let Some(terminal) = terminal {
123
            let _ = terminal.execute(LeaveAlternateScreen);
124
            let _ = terminal.execute(crossterm::cursor::Show);
125
        } else {
126
            let _ = io::stdout().execute(LeaveAlternateScreen);
127
            let _ = io::stdout().execute(crossterm::cursor::Show);
128
        };
129
    }
130
}
131
132
impl Drop for Tui {
133
    fn drop(&mut self) {
134
        Self::restore_terminal(Some(self.terminal.backend_mut()));
135
    }
136
}