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 bf1fc15053bd4ff7d048f438241be4b95daa1b50 6431 bytes (plain)
1
use anyhow::{Ok, Result};
2
use crossterm::{
3
    ExecutableCommand,
4
    event::{self, Event},
5
    terminal::{self, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
6
};
7
use nmrs::{Network, WifiDevice};
8
use ratatui::{
9
    Terminal,
10
    backend::CrosstermBackend,
11
    layout::{Constraint, Direction, Layout},
12
};
13
use std::{
14
    io::stdout,
15
    time::{self, Duration},
16
};
17
18
use crate::{
19
    app::{App, AppEvent},
20
    events,
21
    ui::{
22
        help,
23
        input::{Input},
24
        popup, table,
25
        toast::{self, Toast},
26
    },
27
};
28
29
#[derive(Clone, Copy, PartialEq)]
30
pub enum Tabs {
31
    KnownNetworks,
32
    AvailableNetworks,
33
    Devices,
34
}
35
36
#[derive(Clone, Copy, PartialEq)]
37
pub enum Popups {
38
    Password,
39
}
40
41
#[derive(Clone, Copy)]
42
pub enum Focus {
43
    Tab(Tabs),
44
    Popup(Popups),
45
}
46
47
#[derive(Clone)]
48
pub enum Selected {
49
    Network(Network),
50
    Device(WifiDevice),
51
}
52
53
pub struct Tui {
54
    pub terminal: Terminal<CrosstermBackend<std::io::Stdout>>,
55
56
    pub input: Input,
57
    pub focus: Focus,
58
    pub last_focus: Focus,
59
    pub selected: Option<Selected>,
60
    pub toasts: Vec<Toast>,
61
62
    pub scan: bool,
63
}
64
65
impl Tui {
66
    pub fn new(app: &mut App) -> anyhow::Result<Self> {
67
        let mut stdout = stdout();
68
        enable_raw_mode()?;
69
        stdout
70
            .execute(terminal::EnterAlternateScreen)?
71
            .execute(terminal::Clear(terminal::ClearType::All))?;
72
73
        let backend = CrosstermBackend::new(stdout);
74
        let terminal = Terminal::new(backend)?;
75
76
        app.known_networks.state.select_first();
77
        app.available_networks.state.select_first();
78
        app.devices.state.select_first();
79
80
        Ok(Tui {
81
            terminal,
82
83
            input: Input::new(),
84
            focus: Focus::Tab(Tabs::KnownNetworks),
85
            last_focus: Focus::Tab(Tabs::KnownNetworks),
86
            selected: None,
87
            toasts: Vec::new(),
88
89
            scan: true,
90
        })
91
    }
92
93
    pub fn update_selected(&mut self, app: &App) {
94
        self.selected = match self.focus {
95
            Focus::Tab(tab) => match tab {
96
                Tabs::AvailableNetworks => app
97
                    .available_networks
98
                    .state
99
                    .selected()
100
                    .and_then(|i| app.available_networks.items.get(i))
101
                    .map(|n| Selected::Network(n.clone())),
102
103
                Tabs::KnownNetworks => app
104
                    .known_networks
105
                    .state
106
                    .selected()
107
                    .and_then(|i| app.known_networks.items.get(i))
108
                    .map(|n| Selected::Network(n.clone())),
109
110
                Tabs::Devices => app
111
                    .devices
112
                    .state
113
                    .selected()
114
                    .and_then(|i| app.devices.items.get(i))
115
                    .map(|d| Selected::Device(d.clone())),
116
            },
117
            Focus::Popup(_) => None,
118
        };
119
    }
120
121
    pub fn change_focus(&mut self, new_focus: Focus) {
122
        self.last_focus = self.focus;
123
        self.focus = new_focus;
124
    }
125
126
    pub async fn run(&mut self, app: &mut App) -> Result<()> {
127
        let mut last_tick = time::Instant::now();
128
        let mut rescan_timer = Duration::from_secs(10);
129
        self.update_selected(app);
130
131
        while !app.should_quit {
132
            let now = time::Instant::now();
133
            let delta = now.saturating_duration_since(last_tick);
134
            last_tick = now;
135
136
            // Toast duration timer
137
            self.toasts.iter_mut().for_each(|toast| {
138
                toast.duration = toast.duration.saturating_sub(delta);
139
            });
140
            self.toasts.retain(|toast| !toast.duration.is_zero());
141
142
            // Rescan timer
143
            rescan_timer = rescan_timer.saturating_sub(delta);
144
            if rescan_timer.is_zero() {
145
                app.event_sender.send(AppEvent::Refresh)?;
146
                rescan_timer = Duration::from_secs(10);
147
            }
148
149
            self.terminal.draw(|f| {
150
                let size = f.area();
151
152
                let main_chunks = Layout::default()
153
                    .direction(Direction::Vertical)
154
                    .constraints([Constraint::Length(1), Constraint::Min(0)])
155
                    .split(size);
156
157
                let body_chunks = Layout::new(
158
                    Direction::Vertical,
159
                    [
160
                        Constraint::Percentage(45),
161
                        Constraint::Percentage(45),
162
                        Constraint::Percentage(10),
163
                        Constraint::Length(1),
164
                    ],
165
                )
166
                .split(main_chunks[1]);
167
168
                table::draw_known_network(f, &body_chunks, app, &self.focus);
169
                table::draw_available_network(f, &body_chunks, app, &self.focus);
170
                table::draw_devices(f, &body_chunks, app, &self.focus);
171
                help::draw(f, body_chunks[3], &self.focus);
172
173
                if let Focus::Popup(popup) = self.focus {
174
                    match popup {
175
                        Popups::Password => popup::draw_auth(
176
                            f,
177
                            &self.input,
178
                            &self.selected,
179
                            self.input.hidden_password,
180
                        ),
181
                    }
182
                }
183
184
                toast::draw(f, &self.toasts);
185
            })?;
186
187
            while let std::result::Result::Ok(event) = app.event_receiver.try_recv() {
188
                match event {
189
                    AppEvent::Toast(title, msg, urgency, duration) => {
190
                        self.toasts.push(Toast::new(title, msg, urgency, duration));
191
                    }
192
                    AppEvent::Refresh => {
193
                        if self.scan {
194
                            app.refresh_networks().await?;
195
                            self.update_selected(app);
196
                        }
197
                    }
198
                }
199
            }
200
201
            if event::poll(std::time::Duration::from_millis(200))?
202
                && let Event::Key(key) = event::read()?
203
            {
204
                events::handle_events(app, self, key).await?;
205
            }
206
        }
207
208
        self.cleanup()?;
209
        Ok(())
210
    }
211
212
    // terminal cleanup
213
    fn cleanup(&mut self) -> Result<()> {
214
        disable_raw_mode()?;
215
        self.terminal.backend_mut().execute(LeaveAlternateScreen)?;
216
        self.terminal.show_cursor()?;
217
        Ok(())
218
    }
219
}