index : nmrs-tui
A fast, Vim-friendly NetworkManager TUI built in Rust.
about summary refs log tree commit diff

Diffstat

-rw-r--r-- README.md 10
-rw-r--r-- config.ron 160
-rw-r--r-- src/action.rs 11
-rw-r--r-- src/app.rs 6
-rw-r--r-- src/config.rs 58
-rw-r--r-- src/tui.rs 40
-rw-r--r-- src/ui/area.rs 92
-rw-r--r-- src/ui/margin.rs 54
-rw-r--r-- src/ui/mod.rs 164
-rw-r--r-- src/ui/popup.rs 36
-rw-r--r-- src/ui/style_config.rs 53
-rw-r--r-- src/ui/table.rs 154
-rw-r--r-- src/ui/toast.rs 118
 13 files changed, 651 insertions(+), 305 deletions(-)

diff --git a/README.md b/README.md
index 98deaaf..1b6273c 100644
--- a/README.md
+++ b/README.md
@@ -18,11 +18,11 @@
`nmrs-tui` is a terminal user interface for [nmrs](https://github.com/cachebag/nmrs), inspired from [impala](https://github.com/pythops/impala).

## ✨ Features
- **Available Networks:** Real-time scanning and listing of WiFi networks
- **Known Networks:** Easily manage and connect to your saved profiles
- **Device Management:** View and control your network interfaces
- **Customizable:** (WIP).
- **Vim-like Keybindings:** Navigate your networks with Vim-like keybinds
- **Available Networks:** Real-time scanning and listing of WiFi networks.
- **Known Networks:** Easily manage and connect to your saved profiles.
- **Device Management:** View and control your network interfaces.
- **Customizable:** colors, borders, layout, and table widths are all configurable via a RON config file
- **Vim-like Keybindings:** Navigate your networks with Vim-like keybinds.

## 🚀 Installation

diff --git a/config.ron b/config.ron
index e2f6c70..c408bbd 100644
--- a/config.ron
+++ b/config.ron
@@ -1,3 +1,159 @@
/* @[crate::config::Config] */
Config(
    ui: Ui (
      layout: (
          direction: Vertical,
          panels: [
              (kind: KnownNetworks, constraint: Percentage(50)),
              (kind: AvailableNetworks, constraint: Percentage(50)),
              (kind: Devices, constraint: Min(5)),
              (kind: Help, constraint: Length(1)),
          ],
      ),

Config()
      // Tables
      known_networks: TableConfig ( 
            title: " Known Networks ",
            header: Header (
              columns: [
                ( title: "Name", value: Name, constraint: Percentage(40) ),
                ( title: "Security", value: Security, constraint: Percentage(20) ),
                ( title: "Signal", value: Signal, constraint: Percentage(20) ),
              ],
              style_active: StyleConfig (
                fg: Some("yellow"),
                bold: true
              ),
            ),
            border: Border (
              style_active: StyleConfig(
                fg: Some("green"),
                bold: true
              ),
              type_active: Thick,
            ),
            margin: Margin (top: 1, left: 1, right: 1)
      ),

      available_networks: TableConfig (
            title: " Available Networks ",
            header: Header (
              columns: [
                ( title: "Name", value: Name, constraint: Percentage(40) ),
                ( title: "Security", value: Security, constraint: Percentage(20) ),
                ( title: "Signal", value: Signal, constraint: Percentage(20) ),
              ],
              style_active: StyleConfig (
                fg: Some("yellow"),
                bold: true
              ),
            ),
            border: Border (
              style_active: StyleConfig(
                fg: Some("green"),
                bold: true
              ),
              type_active: Thick,
            ),
            margin: Margin (left: 1, right: 1)
      ),

      devices: TableConfig (
            title: " Devices ",
            header: Header (
              columns: [
                ( title: "Name", value: Name, constraint: Percentage(10) ),
                ( title: "Powered", value: Powered, constraint: Percentage(10) ),
                ( title: "State", value: State, constraint: Percentage(15) ),
                ( title: "Frequency", value: Frequency, constraint: Percentage(15) ),
                ( title: "Address", value: Address, constraint: Percentage(20) ),
                ( title: "Security", value: Security, constraint: Percentage(20) ),
              ],

              style_active: StyleConfig (
                fg: Some("yellow"),
                bold: true
              ),
            ),
            border: Border (
              style_active: StyleConfig(
                fg: Some("green"),
                bold: true
              ),
              type_active: Thick,
            ),
            margin: Margin (left: 1, right: 1)
        ),

        // Popups
        password_popup: PopupConfig (
            width: 60,
            height: 7,
        ),
        toast: ToastConfig (
          normal: UrgencyConfig (
            default_title: "Normal",
            title_style: StyleConfig (
              fg: Some("gray"),
              bold: true
            ),
            border: Border (
              style_normal: StyleConfig(
                fg: Some("gray"),
                bold: true
              ),
              type_active: Thick,
            ),
            default_duration: 3.0,
          ),
          success: UrgencyConfig (
            default_title: "Success",
            title_style: StyleConfig (
              fg: Some("green"),
              bold: true
            ),
            border: Border (
              style_normal: StyleConfig(
                fg: Some("green"),
                bold: true
              ),
              type_active: Thick,
            ),
            default_duration: 3.0,
          ),
          warning: UrgencyConfig (
            default_title: "Warning",
            title_style: StyleConfig (
              fg: Some("yellow"),
              bold: true
            ),
            border: Border (
              style_normal: StyleConfig(
                fg: Some("yellow"),
                bold: true
              ),
              type_active: Thick,
            ),
            default_duration: 6.0,
          ),
          critical: UrgencyConfig (
            default_title: "Critical",
            title_style: StyleConfig (
              fg: Some("red"),
              bold: true
            ),
            border: Border (
              style_normal: StyleConfig(
                fg: Some("red"),
                bold: true
              ),
              type_active: Thick,
            ),
            default_duration: 10.0,
          ),
          position: RightTop,
          margin: Margin (top: 1, right: 1)

        )
    ),

)
diff --git a/src/action.rs b/src/action.rs
index 1f2831a..4864ff6 100644
--- a/src/action.rs
+++ b/src/action.rs
@@ -23,7 +23,6 @@
    NetworkScanResult(Box<(Vec<Network>, Vec<Network>, Vec<WifiDevice>)>),
    Connect(Box<(String, Option<String>, WifiSecurity)>),
    Forget(String),
    #[allow(dead_code)]
    TogglePower,
    Disconnect,

@@ -34,7 +33,7 @@
        Option<Cow<'static, str>>,
        Cow<'static, str>,
        Urgency,
        Option<Duration>,
        Option<f32>,
    ),
}

@@ -273,7 +272,13 @@
                    Tabs::Devices => app.devices.previous(),
                },
                Action::ShowToast(title, msg, urgency, duration) => {
                    app.toasts.push(Toast::new(title, msg, urgency, duration));
                    app.toasts.push(Toast::new(
                        &app.config.ui.toast,
                        title,
                        msg,
                        urgency,
                        duration,
                    ));
                }
            }
        }
diff --git a/src/app.rs b/src/app.rs
index cfc5151..2f34971 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -36,7 +36,7 @@

pub struct App {
    pub action: ActionHandler,
    pub _config: Config,
    pub config: Config,
    pub network_manager: NetworkManager,
    pub should_quit: bool,

@@ -55,7 +55,7 @@
}

impl App {
    pub async fn new(_config: Config) -> Result<Self> {
    pub async fn new(config: Config) -> Result<Self> {
        let action = ActionHandler::new();
        let network_manager = NetworkManager::new().await?;

@@ -65,7 +65,7 @@

        Ok(Self {
            action,
            _config,
            config,
            network_manager,
            should_quit: false,

diff --git a/src/config.rs b/src/config.rs
index 6026755..27bbf52 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -4,21 +4,31 @@
    path::PathBuf,
};

use ron::ser::{self};
use ron::{
    Value,
    ser::{self},
};
use ron::{
    de::{self},
    ser::PrettyConfig,
};
use serde::{Deserialize, Serialize};

use crate::ui::Ui;

const DEFAULT_CONFIG: &str = include_str!("../config.ron");

#[derive(Deserialize, Serialize)]
#[serde(default)]
pub struct Config {}
pub struct Config {
    pub ui: Ui,
}

#[allow(clippy::derivable_impls)]
impl Default for Config {
    fn default() -> Self {
        Self {}
        let config: Self = de::from_str(DEFAULT_CONFIG)
            .map_err(|e| format!("Failed to parse default RON config: {}", e))
            .unwrap();
        config
    }
}

@@ -31,18 +41,23 @@
    }

    pub fn load() -> Result<Self, String> {
        if let Some(config_path) = Self::get_path()
        let default_value: Value = de::from_str(DEFAULT_CONFIG)
            .map_err(|e| format!("Failed to parse default RON config: {}", e))?;

        let merged = if let Some(config_path) = Self::get_path()
            && config_path.exists()
        {
            let config_file = File::open(config_path)
                .map_err(|e| format!("Failed to open config file: {}", e))?;

            let config: Self = de::from_reader(config_file)
            let user_str = fs::read_to_string(&config_path)
                .map_err(|e| format!("Failed to read config file: {}", e))?;
            let user_value: Value = de::from_str(&user_str)
                .map_err(|e| format!("Failed to parse RON config: {}", e))?;
            Ok(config)
            Self::merge_ron(default_value, user_value)
        } else {
            Ok(Self::default())
        }
            default_value
        };
        merged
            .into_rust()
            .map_err(|e| format!("Failed to build config: {}", e))
    }

    pub fn create(&self) -> Result<(), String> {
@@ -63,5 +78,22 @@
            .write_all(ron_string.as_bytes())
            .map_err(|e| format!("Failed to write default config: {}", e))?;
        Ok(())
    }

    pub fn merge_ron(default: Value, user: Value) -> Value {
        match (default, user) {
            (Value::Map(mut default_map), Value::Map(user_map)) => {
                for (k, v) in user_map.iter() {
                    let merged = match default_map.get(k) {
                        Some(dv) => Self::merge_ron(dv.clone(), v.clone()),
                        None => v.clone(),
                    };
                    default_map.insert(k.clone(), merged);
                }
                Value::Map(default_map)
            }
            // scalars/seqs: user value wins outright
            (_, user_value) => user_value,
        }
    }
}
diff --git a/src/tui.rs b/src/tui.rs
index 5e6a553..a78e6e8 100644
--- a/src/tui.rs
+++ b/src/tui.rs
@@ -7,7 +7,7 @@
use ratatui::{
    Frame, Terminal,
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout},
    layout::{Constraint, Layout},
};
use std::{io::stdout, time::Duration};
use tokio::time;
@@ -18,7 +18,7 @@
    app::{App, Focus, Popups, Selected},
    events,
    ui::{
        help, popup, table,
        PanelKind, help, popup, table,
        toast::{self, Urgency},
    },
};
@@ -90,28 +90,28 @@

    fn draw(f: &mut Frame, app: &mut App) {
        let size = f.area();

        let chunks = Layout::new(
            Direction::Vertical,
            [
                Constraint::Percentage(50), // Known Networks
                Constraint::Percentage(50), // Available Networks
                Constraint::Min(5),         // Devices
                Constraint::Length(1),      // Help
            ],
        )
        .split(size);

        table::draw_known_network(f, chunks[0], app);
        table::draw_available_network(f, chunks[1], app);
        table::draw_devices(f, chunks[2], app);
        help::draw(f, chunks[3], app.focus);
        let layout = &app.config.ui.layout;

        let panel_kinds: Vec<PanelKind> =
            app.config.ui.layout.panels.iter().map(|p| p.kind).collect();
        let constraints: Vec<Constraint> = layout.panels.iter().map(|p| p.constraint).collect();

        let chunks = Layout::new(layout.direction, constraints).split(size);

        for (kind, area) in panel_kinds.iter().zip(chunks.iter()) {
            match kind {
                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),
            }
        }

        if let Focus::Popup(popup) = app.focus {
            match popup {
                Popups::Password => {
                    if let Some(Selected::Network(net)) = app.selected() {
                        popup::draw_auth(f, &app.input, net)
                        popup::draw_auth(f, &app.input, net, &app.config.ui.password_popup)
                    } else {
                        app.action.send(Action::ShowToast(
                            None,
@@ -125,7 +125,7 @@
            }
        }

        toast::draw(f, &app.toasts);
        toast::draw(f, &app.config.ui.toast, &app.toasts);
    }

    // terminal cleanup
diff --git a/src/ui/area.rs b/src/ui/area.rs
new file mode 100644
index 0000000..f0d51a3 100644
--- /dev/null
+++ b/src/ui/area.rs
@@ -1,0 +1,92 @@
use ratatui::{layout::Rect, widgets::BorderType};
use serde::{Deserialize, Serialize};

use crate::ui::{margin::Margin, style_config::StyleConfig};

#[derive(Default, Clone, Copy, Deserialize, Serialize)]
pub enum Position {
    LeftTop,
    Top,
    RightTop,

    LeftCenter,
    #[default]
    Center,
    RightCenter,

    LeftBottom,
    Bottom,
    RightBottom,
}

#[derive(Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Border {
    pub style_normal: StyleConfig,
    pub style_active: StyleConfig,
    pub type_normal: BorderType,
    pub type_active: BorderType,
}

// calculate area position
pub fn anchor_rect(
    area: Rect,
    mut width: u16,
    mut height: u16,
    position: Position,
    margin: Margin,
) -> Rect {
    // Make sure that it does not pass the area width and height to prevent crash.
    width = width.min(area.width);
    height = height.min(area.height);

    let x = match position {
        Position::LeftTop | Position::LeftCenter | Position::LeftBottom => 0_u16
            .saturating_add(margin.left)
            .saturating_sub(margin.right),

        Position::Top | Position::Center | Position::Bottom => (area.width.saturating_sub(width)
            / 2)
        .saturating_add(margin.left)
        .saturating_sub(margin.right),

        Position::RightTop | Position::RightCenter | Position::RightBottom => area
            .width
            .saturating_sub(width)
            .saturating_add(margin.left)
            .saturating_sub(margin.right),
    };

    let y = match position {
        Position::LeftTop | Position::Top | Position::RightTop => 0_u16
            .saturating_add(margin.top)
            .saturating_sub(margin.bottom),

        Position::LeftCenter | Position::Center | Position::RightCenter => {
            (area.height.saturating_sub(height) / 2)
                .saturating_add(margin.top)
                .saturating_sub(margin.bottom)
        }

        Position::LeftBottom | Position::Bottom | Position::RightBottom => area
            .height
            .saturating_sub(height)
            .saturating_add(margin.top)
            .saturating_sub(margin.bottom),
    };

    Rect::new(x, y, width, height)
}

pub fn fill_rect(area: Rect, margin: Margin) -> Rect {
    Rect::new(
        area.x.saturating_add(margin.left),
        area.y.saturating_add(margin.top),
        area.width
            .saturating_sub(margin.left)
            .saturating_sub(margin.right),
        area.height
            .saturating_sub(margin.top)
            .saturating_sub(margin.bottom),
    )
}
diff --git a/src/ui/margin.rs b/src/ui/margin.rs
new file mode 100644
index 0000000..739f00e 100644
--- /dev/null
+++ b/src/ui/margin.rs
@@ -1,0 +1,54 @@
use serde::{Deserialize, Serialize};

#[derive(Default, Clone, Copy, Deserialize, Serialize)]
#[serde(default)]
pub struct Margin {
    pub top: u16,
    pub bottom: u16,
    pub left: u16,
    pub right: u16,
}

#[allow(dead_code)]
impl Margin {
    pub fn new(value: u16) -> Self {
        Self {
            top: value,
            bottom: value,
            left: value,
            right: value,
        }
    }

    pub fn horizontal(mut self, value: u16) -> Self {
        self.left = value;
        self.right = value;
        self
    }

    pub fn vertical(mut self, value: u16) -> Self {
        self.top = value;
        self.bottom = value;
        self
    }

    pub fn top(mut self, value: u16) -> Self {
        self.top = value;
        self
    }

    pub fn bottom(mut self, value: u16) -> Self {
        self.bottom = value;
        self
    }

    pub fn left(mut self, value: u16) -> Self {
        self.left = value;
        self
    }

    pub fn right(mut self, value: u16) -> Self {
        self.right = value;
        self
    }
}
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index 6b64e5d..ab2c038 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -1,140 +1,52 @@
use ratatui::layout::Rect;

use ratatui::layout::{Constraint, Direction};
use serde::{Deserialize, Serialize};

use crate::ui::{
    popup::PopupConfig,
    table::{DeviceColumnKind, NetworkColumnKind, TableConfig},
    toast::ToastConfig,
};

pub mod area;
pub mod help;
pub mod input;
pub mod list;
pub mod margin;
pub mod popup;
pub mod style_config;
pub mod table;
pub mod toast;

#[allow(dead_code)]
#[derive(Default)]
pub enum Position {
    #[default]
    LeftTop,
    Top,
    RightTop,

    LeftCenter,
    Center,
    RightCenter,

    LeftBottom,
    Bottom,
    RightBottom,
}

#[derive(Default)]
pub struct Margin {
    top: u16,
    bottom: u16,
    left: u16,
    right: u16,
#[derive(Deserialize, Serialize)]
pub struct Ui {
    pub layout: LayoutConfig,

    // Tables
    pub known_networks: TableConfig<NetworkColumnKind>,
    pub available_networks: TableConfig<NetworkColumnKind>,
    pub devices: TableConfig<DeviceColumnKind>,

    // Popups
    pub password_popup: PopupConfig,
    pub toast: ToastConfig,
}

#[allow(dead_code)]
impl Margin {
    pub fn new(value: u16) -> Self {
        Self {
            top: value,
            bottom: value,
            left: value,
            right: value,
        }
    }

    pub fn horizontal(mut self, value: u16) -> Self {
        self.left = value;
        self.right = value;
        self
    }

    pub fn vertical(mut self, value: u16) -> Self {
        self.top = value;
        self.bottom = value;
        self
    }

    pub fn top(mut self, value: u16) -> Self {
        self.top = value;
        self
    }

    pub fn bottom(mut self, value: u16) -> Self {
        self.bottom = value;
        self
    }

    pub fn left(mut self, value: u16) -> Self {
        self.left = value;
        self
    }

    pub fn right(mut self, value: u16) -> Self {
        self.right = value;
        self
    }
#[derive(Deserialize, Serialize)]
pub struct LayoutConfig {
    pub direction: Direction,
    pub panels: Vec<PanelConfig>,
}

// calculate area position
pub fn anchor_rect(
    area: Rect,
    mut width: u16,
    mut height: u16,
    position: Position,
    margin: Margin,
) -> Rect {
    // Make sure that it does not pass the area width and height to prevent crash.
    width = width.min(area.width);
    height = height.min(area.height);

    let x = match position {
        Position::LeftTop | Position::LeftCenter | Position::LeftBottom => 0_u16
            .saturating_add(margin.left)
            .saturating_sub(margin.right),

        Position::Top | Position::Center | Position::Bottom => (area.width.saturating_sub(width)
            / 2)
        .saturating_add(margin.left)
        .saturating_sub(margin.right),

        Position::RightTop | Position::RightCenter | Position::RightBottom => area
            .width
            .saturating_sub(width)
            .saturating_add(margin.left)
            .saturating_sub(margin.right),
    };

    let y = match position {
        Position::LeftTop | Position::Top | Position::RightTop => 0_u16
            .saturating_add(margin.top)
            .saturating_sub(margin.bottom),

        Position::LeftCenter | Position::Center | Position::RightCenter => {
            (area.height.saturating_sub(height) / 2)
                .saturating_add(margin.top)
                .saturating_sub(margin.bottom)
        }

        Position::LeftBottom | Position::Bottom | Position::RightBottom => area
            .height
            .saturating_sub(height)
            .saturating_add(margin.top)
            .saturating_sub(margin.bottom),
    };

    Rect::new(x, y, width, height)
#[derive(Deserialize, Serialize)]
pub struct PanelConfig {
    pub kind: PanelKind,
    pub constraint: Constraint,
}

pub fn fill_rect(area: Rect, margin: Margin) -> Rect {
    Rect::new(
        area.x.saturating_add(margin.left),
        area.y.saturating_add(margin.top),
        area.width
            .saturating_sub(margin.left)
            .saturating_sub(margin.right),
        area.height
            .saturating_sub(margin.top)
            .saturating_sub(margin.bottom),
    )
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
pub enum PanelKind {
    KnownNetworks,
    AvailableNetworks,
    Devices,
    Help,
}
diff --git a/src/ui/popup.rs b/src/ui/popup.rs
index 0df0502..d47d2a7 100644
--- a/src/ui/popup.rs
+++ b/src/ui/popup.rs
@@ -6,34 +6,38 @@
    text::{Line, Span},
    widgets::{self, Block, BorderType, Paragraph},
};
use serde::{Deserialize, Serialize};

use crate::ui::{self, Margin, Position, input::Input};
use crate::ui::{
    area::{self, Position},
    input::Input,
    margin::Margin,
};

#[derive(Default)]
pub struct Options {
#[derive(Deserialize, Serialize)]
pub struct PopupConfig {
    pub width: u16,
    pub height: u16,
    #[serde(default)]
    pub position: Position,
    #[serde(default)]
    pub margin: Margin,
}

pub fn popup_rect(f: &mut Frame, opt: Options) -> Rect {
    let area = ui::anchor_rect(f.area(), opt.width, opt.height, opt.position, opt.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
}

// TODO: padding.
pub fn draw_auth(f: &mut Frame, input: &Input, network: Network) {
    let popup_rect = popup_rect(
        f,
        Options {
            width: 60,
            height: 7,
            position: Position::Center,
            ..Default::default()
        },
    );
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())
diff --git a/src/ui/style_config.rs b/src/ui/style_config.rs
new file mode 100644
index 0000000..541cb0d 100644
--- /dev/null
+++ b/src/ui/style_config.rs
@@ -1,0 +1,53 @@
use std::str::FromStr;

use anyhow::Context;
use ratatui::style::{Color, ParseColorError, Style};
use serde::{Deserialize, Serialize};

#[derive(Default, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct StyleConfig {
    pub fg: Option<String>,
    pub bg: Option<String>,
    pub bold: bool,
    pub italic: bool,
}

impl StyleConfig {
    pub fn format(&self) -> anyhow::Result<Style> {
        let style: Style = self.clone().try_into().with_context(|| {
            format!(
                "invalid style in config (fg: {:?}, bg: {:?}, bold: {:?}, italic: {:?})",
                self.fg, self.bg, self.bold, self.italic
            )
        })?;
        Ok(style)
    }
}

impl TryFrom<StyleConfig> for Style {
    type Error = ParseColorError;

    fn try_from(config: StyleConfig) -> Result<Self, Self::Error> {
        let mut style = Style::new();
        if let Some(fg_str) = config.fg {
            let color = Color::from_str(&fg_str)?;
            style = style.fg(color);
        }

        if let Some(bg_str) = config.bg {
            let color = Color::from_str(&bg_str)?;
            style = style.bg(color);
        }

        if config.bold {
            style = style.bold();
        }

        if config.italic {
            style = style.italic();
        }

        Ok(style)
    }
}
diff --git a/src/ui/table.rs b/src/ui/table.rs
index 8e7ca1c..3692cfa 100644
--- a/src/ui/table.rs
+++ b/src/ui/table.rs
@@ -1,6 +1,13 @@
use std::hash::Hash;

use crate::{
    app::{App, Focus, Tabs},
    ui::{self, Margin, list::StatefulList},
    ui::{
        area::{self, Border},
        list::StatefulList,
        margin::Margin,
        style_config::StyleConfig,
    },
};
use ratatui::{
    Frame,
@@ -9,32 +16,80 @@
    text::Line,
    widgets::{Block, BorderType, 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 NetworkColumnKind {
    Name,
    Security,
    Signal,
}

pub struct TableData<'a, T> {
    pub title: &'static str,
    pub header_cols: Vec<Line<'a>>,
    pub constraint: Vec<Constraint>,
#[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 draw<Any>(f: &mut Frame, area: Rect, table_data: &mut TableData<Any>, is_active: bool) {
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: Style = if is_active {
        Style::new().bold().green()
        config.border.style_active.format().unwrap_or_default()
    } else {
        Style::new()
        config.border.style_normal.format().unwrap_or_default()
    };

    let border_type: BorderType = if is_active {
        BorderType::Thick
        config.border.type_active
    } else {
        BorderType::Plain
        config.border.type_normal
    };

    let header_style: Style = if is_active {
        Style::new().bold().yellow()
        config.header.style_active.format().unwrap_or_default()
    } else {
        Style::new()
        config.header.style_normal.format().unwrap_or_default()
    };

    let row_style = if is_active {
@@ -42,22 +97,25 @@
    } else {
        Style::new()
    };
    let table = Table::new(table_data.cells.clone(), table_data.constraint.clone())
        .header(
            Row::new(table_data.header_cols.clone())
                .style(header_style)
                .bottom_margin(1),
        )

    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(data.cells.clone(), constraints)
        .header(Row::new(columns).style(header_style).bottom_margin(1))
        .block(
            Block::bordered()
                .title(table_data.title)
                .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 table_data.list.state);
    f.render_stateful_widget(table, area, &mut data.list.state);
}

pub fn draw_known_network(f: &mut Frame<'_>, area: Rect, app: &mut App) {
@@ -123,21 +181,9 @@
        .collect();
    draw(
        f,
        ui::fill_rect(area, Margin::new(0).horizontal(1).top(1)),
        &mut TableData {
            title: " Known Networks ",
            header_cols: vec![
                Line::from("Name").centered(),
                Line::from("Security").centered(),
                Line::from("State").centered(),
                Line::from("Signal").centered(),
            ],
            constraint: vec![
                Constraint::Percentage(40),
                Constraint::Percentage(20),
                Constraint::Percentage(20),
                Constraint::Percentage(20),
            ],
        area,
        &app.config.ui.known_networks,
        &mut Data {
            cells: rows,
            list: &mut app.known_networks,
        },
@@ -194,19 +240,9 @@
        .collect();
    draw(
        f,
        ui::fill_rect(area, Margin::new(0).horizontal(1)),
        &mut TableData {
            title: " Available Networks ",
            header_cols: vec![
                Line::from("Name").centered(),
                Line::from("Security").centered(),
                Line::from("Signal").centered(),
            ],
            constraint: vec![
                Constraint::Percentage(40),
                Constraint::Percentage(20),
                Constraint::Percentage(20),
            ],
        area,
        &app.config.ui.available_networks,
        &mut Data {
            cells: rows,
            list: &mut app.available_networks,
        },
@@ -245,25 +281,9 @@
        .collect();
    draw(
        f,
        ui::fill_rect(area, Margin::new(0).horizontal(1)),
        &mut TableData {
            title: " Devices ",
            header_cols: vec![
                Line::from("Name").centered(),
                Line::from("Powered").centered(),
                Line::from("State").centered(),
                Line::from("Frequency").centered(),
                Line::from("Address").centered(),
                Line::from("Security").centered(),
            ],
            constraint: vec![
                Constraint::Percentage(10),
                Constraint::Percentage(10),
                Constraint::Percentage(15),
                Constraint::Percentage(15),
                Constraint::Percentage(20),
                Constraint::Percentage(20),
            ],
        area,
        &app.config.ui.devices,
        &mut Data {
            cells: rows,
            list: &mut app.devices,
        },
diff --git a/src/ui/toast.rs b/src/ui/toast.rs
index 22943ff..b9addc4 100644
--- a/src/ui/toast.rs
+++ b/src/ui/toast.rs
@@ -3,105 +3,123 @@
use ratatui::{
    Frame,
    layout::Alignment,
    style::Style,
    text::Line,
    widgets::{Block, BorderType, Paragraph},
    widgets::{Block, Paragraph},
};
use serde::{Deserialize, Serialize};

use crate::ui::{
    Margin, Position,
    popup::{self, Options},
    area::{Border, Position},
    margin::Margin,
    popup::{self, PopupConfig},
    style_config::StyleConfig,
};

#[allow(dead_code)]
#[derive(Clone)]
pub struct Toast {
    pub title: Cow<'static, str>,
    pub msg: Cow<'static, str>,
    pub urgency: Urgency,
    pub duration: Duration,
}

#[derive(Deserialize, Serialize)]
pub struct ToastConfig {
    normal: UrgencyConfig,
    success: UrgencyConfig,
    warning: UrgencyConfig,
    critical: UrgencyConfig,
    position: Position,
    margin: Margin,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Urgency {
    Normal,
    Success,
    #[allow(dead_code)]
    Warning,
    Critical,
}

#[derive(Clone)]
pub struct Toast {
    /// Toast title.
    pub title: Cow<'static, str>,
    /// Toast message.
    pub msg: Cow<'static, str>,
    /// Toast Urgency.
    pub urgency: Urgency,
    /// Toast Duration.
    pub duration: Duration,
#[derive(Default, Deserialize, Serialize)]
pub struct UrgencyConfig {
    default_title: String,
    title_style: StyleConfig,
    border: Border,
    default_duration: f32,
}

impl Toast {
    pub fn new<T>(title: Option<T>, msg: T, urgency: Urgency, duration: Option<Duration>) -> Self
    pub fn new<T>(
        config: &ToastConfig,
        title: Option<T>,
        msg: T,
        urgency: Urgency,
        duration: Option<f32>,
    ) -> Self
    where
        T: Into<Cow<'static, str>>,
    {
        let default_duration = match urgency {
            Urgency::Normal | Urgency::Success => Duration::from_secs_f32(3.0),
            Urgency::Warning => Duration::from_secs_f32(6.0),
            Urgency::Critical => Duration::from_secs_f32(10.0),
        let urgency_config = match urgency {
            Urgency::Normal => &config.normal,
            Urgency::Success => &config.success,
            Urgency::Warning => &config.warning,
            Urgency::Critical => &config.critical,
        };

        let title_unwraped: Cow<'static, str> = match title {
        let title: Cow<'static, str> = match title {
            Some(t) => t.into(),
            None => match urgency {
                Urgency::Normal => "Info".into(),
                Urgency::Success => "Success".into(),
                Urgency::Warning => "Warning".into(),
                Urgency::Critical => "Critical".into(),
            },
            None => urgency_config.default_title.clone().into(),
        };

        Self {
            title: title_unwraped,
            title,
            msg: msg.into(),
            urgency,
            duration: duration.unwrap_or(default_duration),
            duration: Duration::from_secs_f32(duration.unwrap_or(urgency_config.default_duration)),
        }
    }
}

pub fn draw(f: &mut Frame, toasts: &[Toast]) {
pub fn draw(f: &mut Frame, config: &ToastConfig, toasts: &[Toast]) {
    for (index, toast) in toasts.iter().enumerate() {
        let area = popup::popup_rect(
            f,
            Options {
            &PopupConfig {
                width: 4 + toast.msg.chars().count() as u16, // 4 = borders(2) + padding(2)
                height: 4,                                   // 4 = borders(2) + title(1) + msg(1)
                position: Position::RightTop,
                position: config.position,
                margin: Margin {
                    top: 1 + (index as u16 * 4),
                    right: 1,
                    ..Default::default()
                    top: config.margin.top + (index as u16 * 4),
                    bottom: config.margin.bottom,
                    left: config.margin.left,
                    right: config.margin.right,
                },
            },
        );

        let border_style = match toast.urgency {
            Urgency::Normal => Style::new().gray(),
            Urgency::Success => Style::new().green(),
            Urgency::Warning => Style::new().yellow(),
            Urgency::Critical => Style::new().red(),
        };

        let title_style = match toast.urgency {
            Urgency::Normal => Style::new().gray(),
            Urgency::Success => Style::new().green(),
            Urgency::Warning => Style::new().yellow(),
            Urgency::Critical => Style::new().red(),
        let urgency_config = match toast.urgency {
            Urgency::Normal => &config.normal,
            Urgency::Success => &config.success,
            Urgency::Warning => &config.warning,
            Urgency::Critical => &config.critical,
        };

        let title = Line::raw(toast.title.as_ref())
            .style(title_style.bold())
            .style(urgency_config.title_style.format().unwrap_or_default())
            .alignment(Alignment::Center);
        let msg = Line::raw(toast.msg.as_ref()).alignment(Alignment::Center);

        let block = Block::bordered()
            .border_style(border_style)
            .border_type(BorderType::Thick);
            .border_style(
                urgency_config
                    .border
                    .style_normal
                    .format()
                    .unwrap_or_default(),
            )
            .border_type(urgency_config.border.type_normal);
        f.render_widget(Paragraph::new(vec![title, msg]).block(block), area);
    }
}