index : nmrs-tui
A fast, Vim-friendly NetworkManager TUI built in Rust.
about summary refs log tree commit diff
nmrs-tui / src / ui / tabs.rs
-rw-r--r-- blob ac837b81b542f4f00c0f5c15e1d3fbf674b336b8 8584 bytes (plain)
1
use crate::{
2
    app::{App, Focus},
3
    ui::{
4
        area::{self, Border},
5
        list::StatefulList,
6
        margin::Margin,
7
        style_config::StyleConfig,
8
    },
9
};
10
use nmrs::{ConnectType, Network, WifiDevice};
11
use ratatui::{
12
    Frame,
13
    layout::{Constraint, Flex, Rect},
14
    style::Style,
15
    text::Line,
16
    widgets::{Block, Row, Table, TableState},
17
};
18
use serde::{Deserialize, Serialize};
19
20
#[derive(Debug, Clone, Copy, PartialEq)]
21
pub enum Tabs {
22
    KnownNetworks,
23
    AvailableNetworks,
24
    Devices,
25
}
26
27
impl Tabs {
28
    pub fn next(self) -> Self {
29
        match self {
30
            Self::KnownNetworks => Self::AvailableNetworks,
31
            Self::AvailableNetworks => Self::Devices,
32
            Self::Devices => Self::KnownNetworks,
33
        }
34
    }
35
36
    pub fn prev(self) -> Self {
37
        match self {
38
            Self::KnownNetworks => Self::Devices,
39
            Self::AvailableNetworks => Self::KnownNetworks,
40
            Self::Devices => Self::AvailableNetworks,
41
        }
42
    }
43
44
    pub fn draw(&self, f: &mut Frame<'_>, area: Rect, app: &mut App) {
45
        let active = matches!(app.focus, Focus::Tab(tab) if tab == *self);
46
47
        match self {
48
            Self::KnownNetworks | Self::AvailableNetworks => {
49
                let (config, list): (&TableConfig<NetworkColumnKind>, &mut StatefulList<Network>) =
50
                    match self {
51
                        Self::KnownNetworks => {
52
                            (&app.config.ui.known_networks, &mut app.known_networks)
53
                        }
54
                        Self::AvailableNetworks => (
55
                            &app.config.ui.available_networks,
56
                            &mut app.available_networks,
57
                        ),
58
                        Self::Devices => unreachable!(),
59
                    };
60
61
                let rows: Vec<Row> = list
62
                    .items
63
                    .iter()
64
                    .map(|net| -> Row<'_> {
65
                        let security = match net.security_features.preferred_connect_type() {
66
                            ConnectType::Open => "Open",
67
                            ConnectType::Psk => "WPA/WPA2",
68
                            ConnectType::Sae => "WPA3",
69
                            ConnectType::Eap => "Enterprise",
70
                            ConnectType::Owe => "OWE",
71
                            _ => "Unknown",
72
                        };
73
74
                        let (strength, bars) = match net.strength {
75
                            Some(strength) => {
76
                                let bars = match strength {
77
                                    81.. => "󰤨",
78
                                    61..=80 => "󰤥",
79
                                    41..=60 => "󰤢",
80
                                    21..=40 => "󰤟",
81
                                    _ => "󰤯",
82
                                };
83
                                (strength.to_string(), bars)
84
                            }
85
                            None => ("Unknown".to_string(), "󰤮"),
86
                        };
87
88
                        let connected = app
89
                            .network_manager
90
                            .current_network
91
                            .as_ref()
92
                            .is_some_and(|current| current.ssid == net.ssid);
93
94
                        let cells: Vec<Line> = config
95
                            .header
96
                            .columns
97
                            .iter()
98
                            .map(|c| match c.value {
99
                                NetworkColumnKind::Name => Line::from(net.ssid.as_str()),
100
                                NetworkColumnKind::Security => Line::from(security),
101
                                NetworkColumnKind::State => {
102
                                    Line::from(if connected { "Connected" } else { "-" })
103
                                }
104
                                NetworkColumnKind::Signal => {
105
                                    Line::from(format!("{}% {}", strength, bars))
106
                                }
107
                            })
108
                            .map(Line::centered)
109
                            .collect();
110
111
                        Row::new(cells)
112
                    })
113
                    .collect();
114
115
                draw(f, area, config, rows, &mut list.state, active);
116
            }
117
118
            Self::Devices => {
119
                let (config, list): (
120
                    &TableConfig<DeviceColumnKind>,
121
                    &mut StatefulList<WifiDevice>,
122
                ) = (&app.config.ui.devices, &mut app.devices);
123
124
                let security: &str = app
125
                    .network_manager
126
                    .current_network_info
127
                    .as_ref()
128
                    .map(|info| info.security.as_str())
129
                    .unwrap_or("-");
130
131
                let rows: Vec<Row> = list
132
                    .items
133
                    .iter()
134
                    .map(|dev| -> Row<'_> {
135
                        let cells: Vec<Line> = config
136
                            .header
137
                            .columns
138
                            .iter()
139
                            .map(|c| match c.value {
140
                                DeviceColumnKind::Name => Line::from(dev.interface.as_str()),
141
                                DeviceColumnKind::Powered => {
142
                                    Line::from(if dev.state.is_enabled() { "On" } else { "Off" })
143
                                }
144
                                DeviceColumnKind::State => Line::from(format!("{}", dev.state)),
145
                                DeviceColumnKind::Frequency => Line::from(format!(
146
                                    "{} MHz",
147
                                    dev.active_frequency_mhz.unwrap_or(0)
148
                                )),
149
                                DeviceColumnKind::Address => Line::from(dev.hw_address.as_str()),
150
                                DeviceColumnKind::Security => Line::from(security),
151
                            })
152
                            .map(Line::centered)
153
                            .collect();
154
155
                        Row::new(cells)
156
                    })
157
                    .collect();
158
159
                draw(f, area, config, rows, &mut list.state, active);
160
            }
161
        }
162
    }
163
}
164
165
#[derive(Deserialize, Serialize)]
166
pub struct TableConfig<K> {
167
    pub title: String,
168
    pub header: Header<K>,
169
    pub border: Border,
170
    #[serde(default)]
171
    pub margin: Margin,
172
}
173
174
#[derive(Deserialize, Serialize)]
175
pub struct Header<K> {
176
    pub columns: Vec<Column<K>>,
177
    #[serde(default)]
178
    pub style_normal: StyleConfig,
179
    #[serde(default)]
180
    pub style_active: StyleConfig,
181
}
182
183
#[derive(Deserialize, Serialize)]
184
pub struct Column<K> {
185
    pub title: String,
186
    pub value: K,
187
    pub constraint: Constraint,
188
}
189
190
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
191
pub enum NetworkColumnKind {
192
    Name,
193
    Security,
194
    State,
195
    Signal,
196
}
197
198
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
199
pub enum DeviceColumnKind {
200
    Name,
201
    Powered,
202
    State,
203
    Frequency,
204
    Address,
205
    Security,
206
}
207
208
pub fn draw<K>(
209
    f: &mut Frame,
210
    area: Rect,
211
    config: &TableConfig<K>,
212
    rows: Vec<Row<'_>>,
213
    state: &mut TableState,
214
    is_active: bool,
215
) {
216
    let area = area::fill_rect(area, config.margin);
217
218
    let (border_style, border_type, header_style, row_style) = if is_active {
219
        (
220
            config.border.style_active.format().unwrap_or_default(),
221
            config.border.type_active,
222
            config.header.style_active.format().unwrap_or_default(),
223
            Style::new().on_dark_gray(),
224
        )
225
    } else {
226
        (
227
            config.border.style_normal.format().unwrap_or_default(),
228
            config.border.type_normal,
229
            config.header.style_normal.format().unwrap_or_default(),
230
            Style::new(),
231
        )
232
    };
233
234
    let (columns, constraints): (Vec<Line>, Vec<Constraint>) = config
235
        .header
236
        .columns
237
        .iter()
238
        .map(|c| (Line::from(c.title.clone()).centered(), c.constraint))
239
        .unzip();
240
    let table = Table::new(rows, constraints)
241
        .header(Row::new(columns).style(header_style).bottom_margin(1))
242
        .block(
243
            Block::bordered()
244
                .title(config.title.clone())
245
                .border_style(border_style)
246
                .border_type(border_type),
247
        )
248
        .flex(Flex::Center)
249
        .row_highlight_style(row_style);
250
251
    f.render_stateful_widget(table, area, state);
252
}