6 files changed, 285 insertions(+), 234 deletions(-)
@@ -4,21 +4,12 @@
use anyhow::Result;
use nmrs::Network;
#[derive(PartialEq)]
pub enum InputMode {
Normal,
Editing,
}
pub struct App {
pub should_quit: bool,
pub network_manager: NetworkManager,
pub devices: StatefulList<nmrs::Device>,
pub known_networks: StatefulList<Network>,
pub input_mode: InputMode,
pub password_input: String,
pub available_networks: StatefulList<Network>,
}
@@ -45,9 +36,6 @@
devices: StatefulList::with_items(device_list),
known_networks: StatefulList::with_items(known_networks_list),
input_mode: InputMode::Normal,
password_input: "".to_string(),
available_networks: StatefulList::with_items(available_networks_list),
})
}
@@ -55,7 +43,7 @@
pub async fn refresh_networks(&mut self) -> Result<()> {
let (known_networks, available_networks) = self.network_manager.scan_networks().await?;
self.known_networks.items = known_networks;
self.new_networks.items = available_networks;
self.available_networks.items = available_networks;
Ok(())
}
@@ -3,12 +3,13 @@
use nmrs::WifiSecurity;
use crate::{
app::{App, InputMode},
app::App,
tui::{Tabs, Tui},
ui::input::InputMode,
};
pub async fn handle_events(app: &mut App, tui: &mut Tui, key: KeyEvent) -> Result<()> {
match app.input_mode {
match tui.input.mode {
InputMode::Normal => match key.code {
KeyCode::Char('q') => app.quit(),
@@ -61,8 +62,7 @@
if let Some(network) = Tui::selected_network(&app.available_networks) {
tui.selected_network = Some(network.clone());
if network.is_psk {
app.password_input.clear();
app.input_mode = InputMode::Editing
tui.input.mode = InputMode::Editing
}
}
}
@@ -80,7 +80,7 @@
},
InputMode::Editing => match key.code {
KeyCode::Enter => {
app.input_mode = InputMode::Normal;
tui.input.mode = InputMode::Normal;
app.network_manager
.connect(
&tui.selected_network.clone().unwrap().ssid,
@@ -90,17 +90,18 @@
},
)
.await?;
app.password_input.clear();
tui.input.value.clear();
tui.input.reset_cursor();
}
KeyCode::Esc => {
app.input_mode = InputMode::Normal;
tui.input.mode = InputMode::Normal;
tui.input.value.clear();
tui.input.reset_cursor();
}
KeyCode::Char(c) => {
app.password_input.push(c);
}
KeyCode::Backspace => {
app.password_input.pop();
}
KeyCode::Char(to_insert) => tui.input.enter_char(to_insert),
KeyCode::Backspace => tui.input.delete_char(),
KeyCode::Left => tui.input.move_cursor_left(),
KeyCode::Right => tui.input.move_cursor_right(),
_ => {}
},
}
@@ -1,5 +1,4 @@
use anyhow::Result;
use std::io::stdout;
#[macro_use] extern crate log;
extern crate simplelog;
@@ -12,9 +11,6 @@
mod ui;
use app::App;
use crossterm::ExecutableCommand;
use crossterm::terminal::{self, enable_raw_mode};
use ratatui::{Terminal, prelude::CrosstermBackend};
use tui::Tui;
use crate::network_manager::NetworkManager;
@@ -27,17 +23,8 @@
let mut app = App::new(network_manager).await?;
let mut tui = Tui::new(&mut app)?;
let mut stdout = stdout();
enable_raw_mode()?;
stdout
.execute(terminal::EnterAlternateScreen)?
.execute(terminal::Clear(terminal::ClearType::All))?;
let backend = CrosstermBackend::new(stdout);
let terminal = Terminal::new(backend)?;
// Start TUI
tui.run(&mut app, terminal).await?;
tui.run(&mut app).await?;
Ok(())
}
@@ -6,19 +6,20 @@
};
use nmrs::Network;
use ratatui::{
Frame, Terminal,
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
widgets::Cell,
};
use ratatui::{layout::Rect, widgets::Row};
use std::{io::stdout, rc::Rc, time::Duration};
use std::{io::stdout, time::Duration};
use crate::{
app::{App, InputMode}, events, ui::{
app::App,
events,
ui::{
self,
input::{Input, InputMode},
list::StatefulList,
table::{self, TableData},
}
},
};
#[derive(PartialEq)]
@@ -31,11 +32,12 @@
pub struct Tui {
pub terminal: Terminal<CrosstermBackend<std::io::Stdout>>,
pub input: Input,
pub active_tab: Tabs,
pub selected_network: Option<Network>,
}
impl<'a> Tui {
impl Tui {
pub fn new(app: &mut App) -> anyhow::Result<Self> {
let mut stdout = stdout();
enable_raw_mode()?;
@@ -59,6 +61,7 @@
Ok(Tui {
terminal,
input: Input::new(),
selected_network: Self::selected_network(&app.available_networks),
active_tab: Tabs::KnownNetworks,
})
@@ -70,13 +73,8 @@
.and_then(|index| list.items.get(index))
.cloned()
}
pub async fn run(
&mut self,
app: &mut App,
mut terminal: Terminal<CrosstermBackend<std::io::Stdout>>,
) -> Result<()> {
pub async fn run(&mut self, app: &mut App) -> Result<()> {
let mut last_tick = tokio::time::Instant::now();
let tick_rate = Duration::from_secs(3);
@@ -87,9 +85,7 @@
}
last_tick = tokio::time::Instant::now();
}
terminal.draw(|f| {
self.terminal.draw(|f| {
let size = f.area();
let main_chunks = Layout::default()
@@ -106,42 +102,11 @@
],
)
.split(main_chunks[1]);
self.render_all_tables(f, body_chunks, app);
if app.input_mode == InputMode::Editing {
self.render_password_popup(f, app);
}
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}
ui::render_all_tables(f, body_chunks, app, &self.active_tab);
if app.input_mode == InputMode::Editing {
let area = centered_rect(60, 20, f.area());
let block = ratatui::widgets::Block::bordered()
.title(" Enter Password ")
.style(ratatui::style::Style::default().fg(ratatui::style::Color::Yellow));
let text =
ratatui::widgets::Paragraph::new(app.password_input.clone()).block(block);
f.render_widget(ratatui::widgets::Clear, area);
f.render_widget(text, area);
if self.input.mode == InputMode::Editing {
ui::render_password_popup(f, &self.input, &self.selected_network);
}
})?;
@@ -154,50 +119,8 @@
self.cleanup()?;
Ok(())
}
fn render_password_popup(&self, f: &mut ratatui::Frame, app: &App) {
let area = self.centered_rect(50, 3, f.area()); // Height 3 for one line + borders
f.render_widget(ratatui::widgets::Clear, area); // Clear the table behind it
// Hide password with asterisks for security
let display_pass: String = app.password_input.chars().map(|_| '*').collect();
let block = ratatui::widgets::Block::bordered()
.title(format!(
" Password for {} ",
self.selected_network
.as_ref()
.map(|n| n.ssid.as_str())
.unwrap_or("Network")
))
.border_style(ratatui::style::Style::default().fg(ratatui::style::Color::Yellow));
let text = ratatui::widgets::Paragraph::new(display_pass).block(block);
f.render_widget(text, area);
}
// Helper to calculate centered rect
fn centered_rect(&self, percent_x: u16, height: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length((r.height.saturating_sub(height)) / 2),
Constraint::Length(height),
Constraint::Min(0),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}
// Helper for terminal cleanup
fn cleanup(&mut self) -> Result<()> {
disable_raw_mode()?;
@@ -206,105 +129,5 @@
.execute(terminal::LeaveAlternateScreen)?;
self.terminal.show_cursor()?;
Ok(())
}
fn render_all_tables(&self, f: &mut Frame<'_>, body_chunks: Rc<[Rect]>, app: &mut App) {
let rows: Vec<Row> = app
.known_networks
.items
.iter()
.map(|net| -> Row<'_> {
Row::new(vec![
Cell::from(net.ssid.clone()),
Cell::from(if net.secured { "Secured" } else { "Open" }),
Cell::from(if app.network_manager.is_connected_cached(&net.ssid) {
"Connected"
} else {
"-"
}),
Cell::from(format!("{}%", net.strength.unwrap_or(0))),
])
})
.collect();
table::draw(
f,
body_chunks[0],
&mut TableData {
title: " Known Networks ",
header_cols: vec!["Name", "Security", "State", "Signal"],
constraint: vec![
Constraint::Percentage(40),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
],
cells: rows,
list: &mut app.known_networks,
},
self.active_tab == Tabs::KnownNetworks,
);
let rows: Vec<Row> = app
.new_networks
.items
.iter()
.map(|net| -> Row<'_> {
Row::new(vec![
Cell::from(net.ssid.clone()),
Cell::from(if net.secured { "Secured" } else { "Open" }),
Cell::from(format!("{}%", net.strength.unwrap_or(0))),
])
})
.collect();
table::draw(
f,
body_chunks[1],
&mut TableData {
title: " Available Networks ",
header_cols: vec!["Name", "Security", "Signal"],
constraint: vec![
Constraint::Percentage(40),
Constraint::Percentage(20),
Constraint::Percentage(20),
],
cells: rows,
list: &mut app.new_networks,
},
self.active_tab == Tabs::AvailableNetworks,
);
let rows: Vec<Row> = app
.devices
.items
.iter()
.map(|net| -> Row<'_> {
Row::new(vec![
Cell::from(net.interface.clone()),
Cell::from(if app.network_manager.enabled {
"On"
} else {
"Off"
}),
// Cell::from(net.dri),
])
})
.collect();
table::draw(
f,
body_chunks[2],
&mut TableData {
title: " Device ",
header_cols: vec!["Name", "Powered", "Scanning", "Frequency", "Security"],
constraint: vec![
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
],
cells: rows,
list: &mut app.devices,
},
self.active_tab == Tabs::Devices,
);
}
}
@@ -1,0 +1,78 @@
#[derive(PartialEq)]
pub enum InputMode {
Normal,
Editing,
}
pub struct Input {
pub mode: InputMode,
pub value: String,
// cursor postion x.
pub cx: usize,
}
impl Input {
pub fn new() -> Self {
Self {
mode: InputMode::Normal,
value: String::new(),
cx: 0,
}
}
pub fn move_cursor_left(&mut self) {
let cursor_moved_left = self.cx.saturating_sub(1);
self.cx = self.clamp_cursor(cursor_moved_left);
}
pub fn move_cursor_right(&mut self) {
let cursor_moved_right = self.cx.saturating_add(1);
self.cx = self.clamp_cursor(cursor_moved_right);
}
pub fn enter_char(&mut self, new_char: char) {
let index = self.byte_index();
self.value.insert(index, new_char);
self.move_cursor_right();
}
// Returns the byte index based on the character position.
// Since each character in a string can contain multiple bytes, it's necessary to calculate
// the byte index based on the index of the character.
fn byte_index(&mut self) -> usize {
self.value
.char_indices()
.map(|(i, _)| i)
.nth(self.cx)
.unwrap_or(self.value.len())
}
pub fn delete_char(&mut self) {
let is_not_cursor_leftmost = self.cx != 0;
if is_not_cursor_leftmost {
// Method "remove" is not used on the saved text for deleting the selected char.
// Reason: Using remove on String works on bytes instead of the chars.
// Using remove would require special care because of char boundaries.
let current_index = self.cx;
let from_left_to_current_index = current_index - 1;
// Getting all characters before the selected character.
let before_char_to_delete = self.value.chars().take(from_left_to_current_index);
// Getting all characters after selected character.
let after_char_to_delete = self.value.chars().skip(current_index);
// Put all characters together except the selected one.
// By leaving the selected one out, it is forgotten and therefore deleted.
self.value = before_char_to_delete.chain(after_char_to_delete).collect();
self.move_cursor_left();
}
}
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;
}
}
@@ -1,2 +1,176 @@
pub mod table;
use std::rc::Rc;
use nmrs::Network;
use ratatui::{
Frame,
layout::{Constraint, Direction, Layout, Position, Rect},
style::{Color, Style, Stylize},
widgets::{Block, Cell, Paragraph, Row},
};
use crate::{
app::App,
tui::Tabs,
ui::{input::Input, table::TableData},
};
pub mod input;
pub mod list;
pub mod table;
// Helper to calculate centered rect
pub fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}
pub fn render_password_popup(f: &mut Frame, input: &Input, selected_network: &Option<Network>) {
// Dim the background.
let dimming_block = ratatui::widgets::Block::default().bg(Color::Black);
f.render_widget(dimming_block, f.area());
let input_area = centered_rect(30, 6, f.area()); // Height 3 for one line + borders
f.render_widget(ratatui::widgets::Clear, input_area); // Clear the table behind it
// Hide password with asterisks for security
let display_pass: String = input.value.chars().map(|_| '*').collect();
let block = Block::bordered()
.title(format!(
" Password for {} ",
selected_network
.as_ref()
.map(|n| n.ssid.as_str())
.unwrap_or("Network")
))
.border_style(Style::default().fg(Color::Yellow));
let text = Paragraph::new(display_pass).block(block);
f.render_widget(text, input_area);
f.set_cursor_position(Position::new(
// Draw the cursor at the current position in the input field.
// This position can be controlled via the left and right arrow key
input_area.x + input.cx as u16 + 1,
// Move one line down, from the border to the input line
input_area.y + 1,
))
}
pub fn render_all_tables(
f: &mut Frame<'_>,
body_chunks: Rc<[Rect]>,
app: &mut App,
active_tab: &Tabs,
) {
let rows: Vec<Row> = app
.known_networks
.items
.iter()
.map(|net| -> Row<'_> {
Row::new(vec![
Cell::from(net.ssid.clone()),
Cell::from(if net.secured { "Secured" } else { "Open" }),
Cell::from(if app.network_manager.is_connected_cached(&net.ssid) {
"Connected"
} else {
"-"
}),
Cell::from(format!("{}%", net.strength.unwrap_or(0))),
])
})
.collect();
table::draw(
f,
body_chunks[0],
&mut TableData {
title: " Known Networks ",
header_cols: vec!["Name", "Security", "State", "Signal"],
constraint: vec![
Constraint::Percentage(40),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
],
cells: rows,
list: &mut app.known_networks,
},
*active_tab == Tabs::KnownNetworks,
);
let rows: Vec<Row> = app
.available_networks
.items
.iter()
.map(|net| -> Row<'_> {
Row::new(vec![
Cell::from(net.ssid.clone()),
Cell::from(if net.secured { "Secured" } else { "Open" }),
Cell::from(format!("{}%", net.strength.unwrap_or(0))),
])
})
.collect();
table::draw(
f,
body_chunks[1],
&mut TableData {
title: " Available Networks ",
header_cols: vec!["Name", "Security", "Signal"],
constraint: vec![
Constraint::Percentage(40),
Constraint::Percentage(20),
Constraint::Percentage(20),
],
cells: rows,
list: &mut app.available_networks,
},
*active_tab == Tabs::AvailableNetworks,
);
let rows: Vec<Row> = app
.devices
.items
.iter()
.map(|net| -> Row<'_> {
Row::new(vec![
Cell::from(net.interface.clone()),
Cell::from(if app.network_manager.enabled {
"On"
} else {
"Off"
}),
])
})
.collect();
table::draw(
f,
body_chunks[2],
&mut TableData {
title: " Device ",
header_cols: vec!["Name", "Powered", "Scanning", "Frequency", "Security"],
constraint: vec![
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
],
cells: rows,
list: &mut app.devices,
},
*active_tab == Tabs::Devices,
);
}