15 files changed, 530 insertions(+), 577 deletions(-)
@@ -1,12 +1,12 @@
use std::{borrow::Cow, time::Duration};
use std::{borrow::Cow, mem, time::Duration};
use nmrs::{ConnectionError, Network, SettingsPatch, WifiDevice, WifiSecurity};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use crate::{
app::{App, Focus, Popups, Status, Tabs},
app::{App, Focus, Status},
ui::{
input::InputMode,
tabs::Tabs,
toast::{Toast, Urgency},
},
};
@@ -18,7 +18,6 @@
Refresh,
SetFocus(Focus),
SetStatus(Status),
SetInputMode(InputMode),
// Network Commands
NetworkScanResult(Box<NetworkScanResult>),
@@ -94,12 +93,6 @@
debug!("Set status to: {:?}!", new_status);
app.status = new_status;
}
Action::SetInputMode(new_inputmode) => {
debug!("Set InputMode to: {:?}!", new_inputmode);
app.input.mode = new_inputmode;
app.input.value.clear();
app.input.reset_cursor();
}
// Network Commands
Action::Refresh => Self::spawn_refresh(app),
@@ -169,15 +162,14 @@
fn set_focus(app: &mut App, new_focus: Focus) {
debug!("Set focus to: {:?}!", new_focus);
app.last_focus = app.focus;
app.focus = new_focus;
match new_focus {
Focus::Popup(Popups::Password) => {
Focus::Popup(_) => {
app.scan.disable();
debug!("Scan disabled (password popup open)");
debug!("Scan disabled (popup is open)");
}
Focus::Tab(_) => app.scan.enable(),
}
app.last_focus = mem::replace(&mut app.focus, new_focus);
}
async fn apply_scan_result(app: &mut App, scan_result: NetworkScanResult) {
@@ -5,41 +5,11 @@
config::Config,
network_manager::NetworkManager,
timer::Timer,
ui::{input::Input, list::StatefulList, toast::Toast},
ui::{list::StatefulList, popup::Popups, tabs::Tabs, toast::Toast},
};
use anyhow::Result;
use nmrs::{Network, WifiDevice};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Tabs {
KnownNetworks,
AvailableNetworks,
Devices,
}
impl Tabs {
pub fn next(self) -> Self {
match self {
Self::KnownNetworks => Self::AvailableNetworks,
Self::AvailableNetworks => Self::Devices,
Self::Devices => Self::KnownNetworks,
}
}
pub fn prev(self) -> Self {
match self {
Self::KnownNetworks => Self::Devices,
Self::AvailableNetworks => Self::KnownNetworks,
Self::Devices => Self::AvailableNetworks,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Popups {
Password,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Status {
// Scanning,
@@ -47,7 +17,7 @@
None,
}
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub enum Focus {
Tab(Tabs),
Popup(Popups),
@@ -67,7 +37,6 @@
// Data
pub status: Status,
pub input: Input,
pub focus: Focus,
pub last_focus: Focus,
pub toasts: Vec<Toast>,
@@ -97,7 +66,6 @@
// Data
status: Status::None,
input: Input::new(),
focus: Focus::Tab(Tabs::KnownNetworks),
last_focus: Focus::Tab(Tabs::KnownNetworks),
toasts: Vec::new(),
@@ -115,13 +83,7 @@
}
pub fn selected(&self) -> Option<Selected> {
let focus = match self.focus {
// If focus is popup we fallback to last_focus so we can get selected
Focus::Popup(_) => self.last_focus,
f => f,
};
match focus {
match &self.focus {
Focus::Tab(Tabs::KnownNetworks) => self
.known_networks
.selected()
@@ -1,127 +1,0 @@
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind};
use nmrs::WifiSecurity;
use crate::{
action::{Action, ConnectRequest},
app::{App, Focus, Popups, Selected, Tabs},
ui::input::InputMode,
};
pub fn handle_events(app: &mut App, key: KeyEvent) {
if key.kind != KeyEventKind::Press {
return;
}
match app.focus {
Focus::Tab(tab) => handle_tabs(app, key, tab),
Focus::Popup(popup) => handle_popups(app, key, popup),
}
}
fn handle_tabs(app: &mut App, key: KeyEvent, tab: Tabs) {
if app.input.mode != InputMode::Normal {
return;
}
match key.code {
KeyCode::Char('q') => app.action.send(Action::Quit),
// Navigation
KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right => {
app.focus = Focus::Tab(tab.next());
}
KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left => {
app.focus = Focus::Tab(tab.prev());
}
KeyCode::Char('j') | KeyCode::Down => app.action.send(Action::NextItem(tab)),
KeyCode::Char('k') | KeyCode::Up => app.action.send(Action::PreviousItem(tab)),
// Global / Tab Actions
KeyCode::Char('r') => app.action.send(Action::Refresh),
KeyCode::Char('a') if tab == Tabs::Devices => {
app.action.send(Action::ToggleAirplaneMode);
}
KeyCode::Char('o') if tab == Tabs::Devices => {
app.action.send(Action::TogglePower);
}
KeyCode::Char('d') if tab == Tabs::KnownNetworks => {
if let Some(Selected::Network(net)) = app.selected() {
app.action.send(Action::Forget { ssid: net.ssid });
}
}
KeyCode::Char('t') if tab == Tabs::KnownNetworks => {
if let Some(Selected::Network(net)) = app.selected() {
app.action
.send(Action::ToggleAutoconnect { ssid: net.ssid });
}
}
KeyCode::Enter | KeyCode::Char(' ') => match tab {
Tabs::KnownNetworks => {
if let Some(Selected::Network(net)) = app.selected() {
let is_connected = app
.network_manager
.current_network
.as_ref()
.is_some_and(|current| current.ssid == net.ssid);
if is_connected {
app.action.send(Action::Disconnect);
} else {
app.action.send(Action::Connect(Box::new(ConnectRequest {
ssid: net.ssid,
interface: None,
credentials: WifiSecurity::Open,
})));
}
}
}
Tabs::AvailableNetworks => {
if let Some(Selected::Network(net)) = app.selected()
&& net.is_psk
{
app.action
.send(Action::SetFocus(Focus::Popup(Popups::Password)));
app.action.send(Action::SetInputMode(InputMode::Editing));
}
}
Tabs::Devices => {}
},
_ => {}
}
}
fn handle_popups(app: &mut App, key: KeyEvent, popup: Popups) {
if app.input.mode != InputMode::Editing {
return;
}
match key.code {
KeyCode::Enter => {
if let Some(Selected::Network(net)) = app.selected() {
app.action.send(Action::Connect(Box::new(ConnectRequest {
ssid: net.ssid,
interface: None,
credentials: WifiSecurity::WpaPsk {
psk: app.input.value.clone(),
},
})));
app.action.send(Action::SetInputMode(InputMode::Normal));
app.action.send(Action::SetFocus(app.last_focus));
}
}
KeyCode::Tab if popup == Popups::Password => {
app.input.hidden_password = !app.input.hidden_password;
}
KeyCode::Char(to_insert) => app.input.enter_char(to_insert),
KeyCode::Backspace => app.input.delete_char(),
KeyCode::Left => app.input.move_cursor_left(),
KeyCode::Right => app.input.move_cursor_right(),
KeyCode::Esc => {
app.action.send(Action::SetInputMode(InputMode::Normal));
app.action.send(Action::SetFocus(app.last_focus));
}
_ => {}
}
}
@@ -15,9 +15,9 @@
use crate::{
action::{Action, ActionHandler},
app::{App, Focus, Popups, Selected},
app::{App, Focus},
events,
ui::{PanelKind, header, help, popup, table, toast},
ui::{PanelKind, header, help, tabs::Tabs, toast},
};
pub struct Tui {
@@ -81,21 +81,15 @@
for (kind, area) in panel_kinds.into_iter().zip(chunks.iter()) {
match kind {
PanelKind::Header => header::draw(f, *area, app),
PanelKind::KnownNetworks => table::draw_known_network(f, *area, app),
PanelKind::AvailableNetworks => table::draw_available_network(f, *area, app),
PanelKind::Devices => table::draw_devices(f, *area, app),
PanelKind::Help => help::draw(f, *area, app.focus),
PanelKind::KnownNetworks => Tabs::KnownNetworks.draw(f, *area, app),
PanelKind::AvailableNetworks => Tabs::AvailableNetworks.draw(f, *area, app),
PanelKind::Devices => Tabs::Devices.draw(f, *area, app),
PanelKind::Help => help::draw(f, *area, &app.focus),
}
}
if let Focus::Popup(Popups::Password) = app.focus {
if let Some(Selected::Network(net)) = app.selected() {
popup::draw_auth(f, &app.input, &net, &app.config.ui.password_popup);
} else {
app.action
.send(Action::toast_err("Can't find selected network"));
app.action.send(Action::SetFocus(app.last_focus));
}
if let Focus::Popup(popup) = &app.focus {
popup.draw(f, &app.config.ui);
}
toast::draw(f, &app.config.ui.toast, &app.toasts);
@@ -1,0 +1,16 @@
use crate::app::{App, Focus};
use crossterm::event::{KeyEvent, KeyEventKind};
mod popups;
mod tabs;
pub fn handle_events(app: &mut App, key: KeyEvent) {
if key.kind != KeyEventKind::Press {
return;
}
match app.focus {
Focus::Tab(tab) => tabs::handle(app, key, tab),
Focus::Popup(_) => popups::handle(app, key),
}
}
@@ -1,0 +1,44 @@
use crossterm::event::{KeyCode, KeyEvent};
use nmrs::WifiSecurity;
use crate::{
action::{Action, ConnectRequest},
app::{App, Focus},
ui::popup::Popups,
};
pub fn handle(app: &mut App, key: KeyEvent) {
let Focus::Popup(popup) = &mut app.focus else {
return;
};
match popup {
Popups::Password(input, network) => match key.code {
// Connect
KeyCode::Enter => {
app.action.send(Action::Connect(Box::new(ConnectRequest {
ssid: network.ssid.clone(),
interface: None,
credentials: WifiSecurity::WpaPsk {
psk: input.value.clone(),
},
})));
popup.close(&app.action, app.last_focus.clone());
}
// Hide the password
KeyCode::Tab => {
input.hidden = !input.hidden;
}
KeyCode::Char(to_insert) => input.enter_char(to_insert),
KeyCode::Backspace => input.delete_char(),
KeyCode::Left => input.move_cursor_left(),
KeyCode::Right => input.move_cursor_right(),
KeyCode::Esc => {
popup.close(&app.action, app.last_focus.clone());
}
_ => {}
},
}
}
@@ -1,0 +1,76 @@
use crossterm::event::{KeyCode, KeyEvent};
use nmrs::WifiSecurity;
use crate::{
action::{Action, ConnectRequest},
app::{App, Focus, Selected},
ui::{input::Input, popup::Popups, tabs::Tabs},
};
pub fn handle(app: &mut App, key: KeyEvent, tab: Tabs) {
match key.code {
KeyCode::Char('q') => app.action.send(Action::Quit),
// Navigation
KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right => {
app.action.send(Action::SetFocus(Focus::Tab(tab.next())));
}
KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left => {
app.action.send(Action::SetFocus(Focus::Tab(tab.prev())));
}
KeyCode::Char('j') | KeyCode::Down => app.action.send(Action::NextItem(tab)),
KeyCode::Char('k') | KeyCode::Up => app.action.send(Action::PreviousItem(tab)),
// Global / Tab Actions
KeyCode::Char('r') => app.action.send(Action::Refresh),
KeyCode::Char('a') if tab == Tabs::Devices => {
app.action.send(Action::ToggleAirplaneMode);
}
KeyCode::Char('o') if tab == Tabs::Devices => {
app.action.send(Action::TogglePower);
}
KeyCode::Char('d') if tab == Tabs::KnownNetworks => {
if let Some(Selected::Network(net)) = app.selected() {
app.action.send(Action::Forget { ssid: net.ssid });
}
}
KeyCode::Char('t') if tab == Tabs::KnownNetworks => {
if let Some(Selected::Network(net)) = app.selected() {
app.action
.send(Action::ToggleAutoconnect { ssid: net.ssid });
}
}
KeyCode::Enter | KeyCode::Char(' ') => match tab {
Tabs::KnownNetworks => {
if let Some(Selected::Network(net)) = app.selected() {
let is_connected = app
.network_manager
.current_network
.as_ref()
.is_some_and(|current| current.ssid == net.ssid);
if is_connected {
app.action.send(Action::Disconnect);
} else {
app.action.send(Action::Connect(Box::new(ConnectRequest {
ssid: net.ssid,
interface: None,
credentials: WifiSecurity::Open,
})));
}
}
}
Tabs::AvailableNetworks => {
if let Some(Selected::Network(net)) = app.selected()
&& net.is_psk
{
Popups::Password(Input::new(), Box::new(net)).open(&app.action);
}
}
Tabs::Devices => {}
},
_ => {}
}
}
@@ -5,16 +5,13 @@
text::{Line, Span},
};
use crate::{
app::{App, Status},
ui::table::network_info,
};
use crate::app::{App, Status};
pub fn draw(f: &mut Frame<'_>, area: Rect, app: &App) {
let chunks = Layout::horizontal([
Constraint::Fill(12),
Constraint::Fill(1),
Constraint::Fill(1),
Constraint::Fill(1),
])
.split(area);
@@ -36,7 +33,20 @@
// Right: Currently connected network
let right_line = if let Some(current) = &app.network_manager.current_network {
let (_, strength, bars) = network_info(current);
let (strength, bars) = match current.strength {
Some(strength) => {
let bars = match strength {
81.. => "",
61..=80 => "",
41..=60 => "",
21..=40 => "",
_ => "",
};
(strength.to_string(), bars)
}
None => ("Unknown".to_string(), ""),
};
Line::from(vec![
Span::styled(format!("{} ", bars), Style::new().fg(Color::Green)),
Span::raw(format!("{} ({}%) ", current.ssid, strength)),
@@ -5,9 +5,12 @@
widgets::Paragraph,
};
use crate::app::{Focus, Popups, Tabs};
use crate::{
app::Focus,
ui::{popup::Popups, tabs::Tabs},
};
pub fn draw(f: &mut Frame, area: Rect, focus: Focus) {
pub fn draw(f: &mut Frame, area: Rect, focus: &Focus) {
let help_msg = match focus {
Focus::Tab(Tabs::KnownNetworks) => {
"k, Up | j, Down | or ↵ Dis/connect | d Forget | t Autoconnect | r Scan | ⇄ Nav"
@@ -16,7 +19,7 @@
"k, Up | j, Down | or ↵ Connect | r Scan | ⇄ Nav"
}
Focus::Tab(Tabs::Devices) => "r Scan | o Toggle Power | a Toggle Airplane | ⇄ Nav",
Focus::Popup(Popups::Password) => "↵ Apply | ⇄ Hide/Show password | Discard",
Focus::Popup(Popups::Password(_, _)) => "↵ Apply | ⇄ Hide/Show password | Discard",
};
f.render_widget(
@@ -1,13 +1,9 @@
#[derive(Debug, Clone, PartialEq)]
pub enum InputMode {
Normal,
Editing,
}
#[derive(Debug, Clone)]
pub struct Input {
pub mode: InputMode,
/// Input value
pub value: String,
pub hidden_password: bool,
/// Hide the value in asterisk
pub hidden: bool,
/// Cursor postion x.
pub cx: usize,
}
@@ -15,9 +11,8 @@
impl Input {
pub fn new() -> Self {
Self {
mode: InputMode::Normal,
value: String::new(),
hidden_password: true,
hidden: true,
cx: 0,
}
}
@@ -73,9 +68,5 @@
fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
new_cursor_pos.clamp(0, self.value.chars().count())
}
pub const fn reset_cursor(&mut self) {
self.cx = 0;
}
}
@@ -3,7 +3,7 @@
use crate::ui::{
popup::PopupConfig,
table::{AvailableNetworkColumnKind, DeviceColumnKind, KnownNetworkColumnKind, TableConfig},
tabs::{DeviceColumnKind, NetworkColumnKind, TableConfig},
toast::ToastConfig,
};
@@ -15,7 +15,7 @@
pub mod margin;
pub mod popup;
pub mod style_config;
pub mod table;
pub mod tabs;
pub mod toast;
#[derive(Deserialize, Serialize)]
@@ -23,8 +23,8 @@
pub layout: LayoutConfig,
// Tables
pub known_networks: TableConfig<KnownNetworkColumnKind>,
pub available_networks: TableConfig<AvailableNetworkColumnKind>,
pub known_networks: TableConfig<NetworkColumnKind>,
pub available_networks: TableConfig<NetworkColumnKind>,
pub devices: TableConfig<DeviceColumnKind>,
// Popups
@@ -8,12 +8,100 @@
};
use serde::{Deserialize, Serialize};
use crate::ui::{
area::{self, Position},
input::Input,
margin::Margin,
use crate::{
action::{Action, ActionHandler},
app::Focus,
ui::{
Ui,
area::{self, Position},
input::Input,
margin::Margin,
},
};
#[derive(Debug, Clone)]
pub enum Popups {
Password(Input, Box<Network>),
}
impl Popups {
pub fn open(self, action: &ActionHandler) {
action.send(Action::SetFocus(Focus::Popup(self)));
}
pub fn close(&self, action: &ActionHandler, last_focus: Focus) {
action.send(Action::SetFocus(last_focus));
}
pub fn rect(f: &mut Frame, config: &PopupConfig) -> Rect {
let area = area::anchor_rect(
f.area(),
config.width,
config.height,
config.position,
config.margin,
);
f.render_widget(widgets::Clear, area); // Clear the area behind it
area
}
pub fn draw(&self, f: &mut Frame, config: &Ui) {
match self {
Self::Password(input, network) => {
let rect = Popups::rect(f, &config.password_popup);
let block = Block::bordered()
.border_style(Style::default().green().bold())
.border_type(BorderType::Thick);
let title = Line::from(vec![
Span::raw("Enter the password for "),
Span::styled(&network.ssid, Style::new().bold()),
])
.alignment(Alignment::Center);
let title_widget = Paragraph::new(title).block(block);
f.render_widget(title_widget, rect);
let input_area = Rect::new(rect.x + 1, rect.y + 3, rect.width.saturating_sub(2), 1);
let input_chunks = Layout::horizontal([
Constraint::Min(0), // Password input
Constraint::Length(4), // eye icon
])
.split(input_area);
let (mut password, icon): (String, &'static str) = if input.hidden {
(input.value.chars().map(|_| '*').collect(), " ")
} else {
(input.value.to_string(), " ")
};
// Horizontal scrolling when password is to long
let string_offset = password
.len()
.saturating_sub(input_chunks[0].width.saturating_sub(1) as usize);
if string_offset > 0 {
password = password.split_at(string_offset).1.to_string();
}
let password_widget = Paragraph::new(password).style(Style::new().on_dark_gray());
f.render_widget(password_widget, input_chunks[0]);
let icon_widget = Paragraph::new(icon).style(Style::new().green());
f.render_widget(icon_widget, input_chunks[1]);
// Cursor position x
let cx = input_chunks[0].x + input.cx as u16;
// cx_max = position + width - 1 (so the cursor does overlap on eye icon)
let cx_max = input_chunks[0].x + input_chunks[0].width.saturating_sub(1);
f.set_cursor_position(layout::Position::new(cx.min(cx_max), input_chunks[0].y))
}
}
}
}
#[derive(Deserialize, Serialize)]
pub struct PopupConfig {
pub width: u16,
@@ -22,73 +110,4 @@
pub position: Position,
#[serde(default)]
pub margin: Margin,
}
pub fn popup_rect(f: &mut Frame, config: &PopupConfig) -> Rect {
let area = area::anchor_rect(
f.area(),
config.width,
config.height,
config.position,
config.margin,
);
f.render_widget(widgets::Clear, area); // Clear the area behind it
area
}
pub fn draw_auth(f: &mut Frame, input: &Input, network: &Network, config: &PopupConfig) {
let popup_rect = popup_rect(f, config);
let block = Block::bordered()
.border_style(Style::default().green().bold())
.border_type(BorderType::Thick);
let title = Line::from(vec![
Span::raw("Enter the password for "),
Span::styled(&network.ssid, Style::new().bold()),
])
.alignment(Alignment::Center);
let title_widget = Paragraph::new(title).block(block);
f.render_widget(title_widget, popup_rect);
let input_area = Rect::new(
popup_rect.x + 1,
popup_rect.y + 3,
popup_rect.width.saturating_sub(2),
1,
);
let input_chunks = Layout::horizontal([
Constraint::Min(0), // Password input
Constraint::Length(4), // eye icon
])
.split(input_area);
let (mut password, icon): (String, &'static str) = if input.hidden_password {
(input.value.chars().map(|_| '*').collect(), " ")
} else {
(input.value.to_string(), " ")
};
// Horizontal scrolling when password is to long
let string_offset = password
.len()
.saturating_sub(input_chunks[0].width.saturating_sub(1) as usize);
if string_offset > 0 {
password = password.split_at(string_offset).1.to_string();
}
let password_widget = Paragraph::new(password).style(Style::new().on_dark_gray());
f.render_widget(password_widget, input_chunks[0]);
let icon_widget = Paragraph::new(icon).style(Style::new().green());
f.render_widget(icon_widget, input_chunks[1]);
// Cursor position x
let cx = input_chunks[0].x + input.cx as u16;
// cx_max = position + width - 1 (so the cursor does overlap on eye icon)
let cx_max = input_chunks[0].x + input_chunks[0].width.saturating_sub(1);
f.set_cursor_position(layout::Position::new(cx.min(cx_max), input_chunks[0].y))
}
@@ -1,279 +1,0 @@
use std::{hash::Hash, mem};
use crate::{
app::{App, Focus, Tabs},
ui::{
area::{self, Border},
list::StatefulList,
margin::Margin,
style_config::StyleConfig,
},
};
use nmrs::Network;
use ratatui::{
Frame,
layout::{Constraint, Flex, Rect},
style::Style,
text::Line,
widgets::{Block, Row, Table},
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
pub struct TableConfig<K> {
pub title: String,
pub header: Header<K>,
pub border: Border,
#[serde(default)]
pub margin: Margin,
}
#[derive(Deserialize, Serialize)]
pub struct Header<K> {
pub columns: Vec<Column<K>>,
#[serde(default)]
pub style_normal: StyleConfig,
#[serde(default)]
pub style_active: StyleConfig,
}
#[derive(Deserialize, Serialize)]
pub struct Column<K> {
pub title: String,
pub value: K,
pub constraint: Constraint,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum KnownNetworkColumnKind {
Name,
Security,
State,
Signal,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum AvailableNetworkColumnKind {
Name,
Security,
Signal,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum DeviceColumnKind {
Name,
Powered,
State,
Frequency,
Address,
Security,
}
pub struct Data<'a, T> {
pub cells: Vec<Row<'a>>,
pub list: &'a mut StatefulList<T>,
}
pub fn network_info<'a>(net: &Network) -> (&'a str, String, &'a str) {
let security = if net.is_psk {
"Psk"
} else if net.is_eap {
"Enterprise"
} else if net.secured {
"Other"
} else {
"Open"
};
let (strength, bars) = match net.strength {
Some(strength) => {
let bars = match strength {
81.. => "",
61..=80 => "",
41..=60 => "",
21..=40 => "",
_ => "",
};
(strength.to_string(), bars)
}
None => ("Unknown".to_string(), ""),
};
(security, strength, bars)
}
pub fn draw<Any, K: Eq + Hash>(
f: &mut Frame,
area: Rect,
config: &TableConfig<K>,
data: &mut Data<Any>,
is_active: bool,
) {
let area = area::fill_rect(area, config.margin);
let (border_style, border_type, header_style, row_style) = if is_active {
(
config.border.style_active.format().unwrap_or_default(),
config.border.type_active,
config.header.style_active.format().unwrap_or_default(),
Style::new().on_dark_gray(),
)
} else {
(
config.border.style_normal.format().unwrap_or_default(),
config.border.type_normal,
config.header.style_normal.format().unwrap_or_default(),
Style::new(),
)
};
let (columns, constraints): (Vec<Line>, Vec<Constraint>) = config
.header
.columns
.iter()
.map(|c| (Line::from(c.title.clone()).centered(), c.constraint))
.unzip();
let table = Table::new(mem::take(&mut data.cells), constraints)
.header(Row::new(columns).style(header_style).bottom_margin(1))
.block(
Block::bordered()
.title(config.title.clone())
.border_style(border_style)
.border_type(border_type),
)
.flex(Flex::Center)
.row_highlight_style(row_style);
f.render_stateful_widget(table, area, &mut data.list.state);
}
pub fn draw_known_network(f: &mut Frame<'_>, area: Rect, app: &mut App) {
let active = matches!(app.focus, Focus::Tab(Tabs::KnownNetworks));
let columns = &app.config.ui.known_networks.header.columns;
let rows: Vec<Row> = app
.known_networks
.items
.iter()
.map(|net| -> Row<'_> {
let (security, strength, bars) = network_info(net);
let connected = app
.network_manager
.current_network
.as_ref()
.is_some_and(|current| current.ssid == net.ssid);
let cells: Vec<Line> = columns
.iter()
.map(|c| match c.value {
KnownNetworkColumnKind::Name => Line::from(net.ssid.clone()),
KnownNetworkColumnKind::Security => Line::from(security),
KnownNetworkColumnKind::State => {
Line::from(if connected { "Connected" } else { "-" })
}
KnownNetworkColumnKind::Signal => Line::from(format!("{}% {}", strength, bars)),
})
.map(|line| line.centered())
.collect();
Row::new(cells)
})
.collect();
draw(
f,
area,
&app.config.ui.known_networks,
&mut Data {
cells: rows,
list: &mut app.known_networks,
},
active,
);
}
pub fn draw_available_network(f: &mut Frame<'_>, area: Rect, app: &mut App) {
let active = matches!(app.focus, Focus::Tab(Tabs::AvailableNetworks));
let columns = &app.config.ui.available_networks.header.columns;
let rows: Vec<Row> = app
.available_networks
.items
.iter()
.map(|net| -> Row<'_> {
let (security, strength, bars) = network_info(net);
let cells: Vec<Line> = columns
.iter()
.map(|c| match c.value {
AvailableNetworkColumnKind::Name => Line::from(net.ssid.clone()),
AvailableNetworkColumnKind::Security => Line::from(security),
AvailableNetworkColumnKind::Signal => {
Line::from(format!("{}% {}", strength, bars))
}
})
.map(|line| line.centered())
.collect();
Row::new(cells)
})
.collect();
draw(
f,
area,
&app.config.ui.available_networks,
&mut Data {
cells: rows,
list: &mut app.available_networks,
},
active,
);
}
pub fn draw_devices(f: &mut Frame<'_>, area: Rect, app: &mut App) {
let active = matches!(app.focus, Focus::Tab(Tabs::Devices));
let columns = &app.config.ui.devices.header.columns;
let security: String = app
.network_manager
.current_network_info
.as_ref()
.map(|info| info.security.clone())
.unwrap_or_else(|| "-".to_string());
let rows: Vec<Row> = app
.devices
.items
.iter()
.map(|dev| -> Row<'_> {
let cells: Vec<Line> = columns
.iter()
.map(|c| match c.value {
DeviceColumnKind::Name => Line::from(dev.interface.clone()),
DeviceColumnKind::Powered => {
Line::from(if dev.state.is_enabled() { "On" } else { "Off" })
}
DeviceColumnKind::State => Line::from(format!("{}", dev.state)),
DeviceColumnKind::Frequency => {
Line::from(format!("{} MHz", dev.active_frequency_mhz.unwrap_or(0)))
}
DeviceColumnKind::Address => Line::from(dev.hw_address.to_string()),
DeviceColumnKind::Security => Line::from(security.clone()),
})
.map(|line| line.centered())
.collect();
Row::new(cells)
})
.collect();
draw(
f,
area,
&app.config.ui.devices,
&mut Data {
cells: rows,
list: &mut app.devices,
},
active,
);
}
@@ -1,0 +1,252 @@
use crate::{
app::{App, Focus},
ui::{
area::{self, Border},
list::StatefulList,
margin::Margin,
style_config::StyleConfig,
},
};
use nmrs::{ConnectType, Network, WifiDevice};
use ratatui::{
Frame,
layout::{Constraint, Flex, Rect},
style::Style,
text::Line,
widgets::{Block, Row, Table, TableState},
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Tabs {
KnownNetworks,
AvailableNetworks,
Devices,
}
impl Tabs {
pub fn next(self) -> Self {
match self {
Self::KnownNetworks => Self::AvailableNetworks,
Self::AvailableNetworks => Self::Devices,
Self::Devices => Self::KnownNetworks,
}
}
pub fn prev(self) -> Self {
match self {
Self::KnownNetworks => Self::Devices,
Self::AvailableNetworks => Self::KnownNetworks,
Self::Devices => Self::AvailableNetworks,
}
}
pub fn draw(&self, f: &mut Frame<'_>, area: Rect, app: &mut App) {
let active = matches!(app.focus, Focus::Tab(tab) if tab == *self);
match self {
Self::KnownNetworks | Self::AvailableNetworks => {
let (config, list): (&TableConfig<NetworkColumnKind>, &mut StatefulList<Network>) =
match self {
Self::KnownNetworks => {
(&app.config.ui.known_networks, &mut app.known_networks)
}
Self::AvailableNetworks => (
&app.config.ui.available_networks,
&mut app.available_networks,
),
Self::Devices => unreachable!(),
};
let rows: Vec<Row> = list
.items
.iter()
.map(|net| -> Row<'_> {
let security = match net.security_features.preferred_connect_type() {
ConnectType::Open => "Open",
ConnectType::Psk => "WPA/WPA2",
ConnectType::Sae => "WPA3",
ConnectType::Eap => "Enterprise",
ConnectType::Owe => "OWE",
_ => "Unknown",
};
let (strength, bars) = match net.strength {
Some(strength) => {
let bars = match strength {
81.. => "",
61..=80 => "",
41..=60 => "",
21..=40 => "",
_ => "",
};
(strength.to_string(), bars)
}
None => ("Unknown".to_string(), ""),
};
let connected = app
.network_manager
.current_network
.as_ref()
.is_some_and(|current| current.ssid == net.ssid);
let cells: Vec<Line> = config
.header
.columns
.iter()
.map(|c| match c.value {
NetworkColumnKind::Name => Line::from(net.ssid.as_str()),
NetworkColumnKind::Security => Line::from(security),
NetworkColumnKind::State => {
Line::from(if connected { "Connected" } else { "-" })
}
NetworkColumnKind::Signal => {
Line::from(format!("{}% {}", strength, bars))
}
})
.map(Line::centered)
.collect();
Row::new(cells)
})
.collect();
draw(f, area, config, rows, &mut list.state, active);
}
Self::Devices => {
let (config, list): (
&TableConfig<DeviceColumnKind>,
&mut StatefulList<WifiDevice>,
) = (&app.config.ui.devices, &mut app.devices);
let security: &str = app
.network_manager
.current_network_info
.as_ref()
.map(|info| info.security.as_str())
.unwrap_or("-");
let rows: Vec<Row> = list
.items
.iter()
.map(|dev| -> Row<'_> {
let cells: Vec<Line> = config
.header
.columns
.iter()
.map(|c| match c.value {
DeviceColumnKind::Name => Line::from(dev.interface.as_str()),
DeviceColumnKind::Powered => {
Line::from(if dev.state.is_enabled() { "On" } else { "Off" })
}
DeviceColumnKind::State => Line::from(format!("{}", dev.state)),
DeviceColumnKind::Frequency => Line::from(format!(
"{} MHz",
dev.active_frequency_mhz.unwrap_or(0)
)),
DeviceColumnKind::Address => Line::from(dev.hw_address.as_str()),
DeviceColumnKind::Security => Line::from(security),
})
.map(Line::centered)
.collect();
Row::new(cells)
})
.collect();
draw(f, area, config, rows, &mut list.state, active);
}
}
}
}
#[derive(Deserialize, Serialize)]
pub struct TableConfig<K> {
pub title: String,
pub header: Header<K>,
pub border: Border,
#[serde(default)]
pub margin: Margin,
}
#[derive(Deserialize, Serialize)]
pub struct Header<K> {
pub columns: Vec<Column<K>>,
#[serde(default)]
pub style_normal: StyleConfig,
#[serde(default)]
pub style_active: StyleConfig,
}
#[derive(Deserialize, Serialize)]
pub struct Column<K> {
pub title: String,
pub value: K,
pub constraint: Constraint,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum NetworkColumnKind {
Name,
Security,
State,
Signal,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
pub enum DeviceColumnKind {
Name,
Powered,
State,
Frequency,
Address,
Security,
}
pub fn draw<K>(
f: &mut Frame,
area: Rect,
config: &TableConfig<K>,
rows: Vec<Row<'_>>,
state: &mut TableState,
is_active: bool,
) {
let area = area::fill_rect(area, config.margin);
let (border_style, border_type, header_style, row_style) = if is_active {
(
config.border.style_active.format().unwrap_or_default(),
config.border.type_active,
config.header.style_active.format().unwrap_or_default(),
Style::new().on_dark_gray(),
)
} else {
(
config.border.style_normal.format().unwrap_or_default(),
config.border.type_normal,
config.header.style_normal.format().unwrap_or_default(),
Style::new(),
)
};
let (columns, constraints): (Vec<Line>, Vec<Constraint>) = config
.header
.columns
.iter()
.map(|c| (Line::from(c.title.clone()).centered(), c.constraint))
.unzip();
let table = Table::new(rows, constraints)
.header(Row::new(columns).style(header_style).bottom_margin(1))
.block(
Block::bordered()
.title(config.title.clone())
.border_style(border_style)
.border_type(border_type),
)
.flex(Flex::Center)
.row_highlight_style(row_style);
f.render_stateful_widget(table, area, state);
}
@@ -11,7 +11,7 @@
use crate::ui::{
area::{Border, Position},
margin::Margin,
popup::{self, PopupConfig},
popup::{PopupConfig, Popups},
style_config::StyleConfig,
};
@@ -99,7 +99,7 @@
break;
};
let area = popup::popup_rect(
let area = Popups::rect(
f,
&PopupConfig {
width: 4 + toast.msg.chars().count() as u16, // 4 = borders(2) + padding(2)