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

Diffstat

-rw-r--r-- src/app.rs 23
-rw-r--r-- src/events.rs 44
-rw-r--r-- src/main.rs 5
-rw-r--r-- src/network_manager.rs 77
-rw-r--r-- src/tui.rs 72
-rw-r--r-- src/ui/input.rs 2
-rw-r--r-- src/ui/mod.rs 30
-rw-r--r-- src/ui/popup.rs 112
-rw-r--r-- src/ui/table.rs 14
-rw-r--r-- src/ui/toast.rs 98
 10 files changed, 341 insertions(+), 136 deletions(-)

diff --git a/src/app.rs b/src/app.rs
index 5ab463f..e46177b 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -1,6 +1,17 @@
use crate::{network_manager::NetworkManager, ui::list::StatefulList};
use std::{borrow::Cow, time::Duration};

use crate::{
    network_manager::NetworkManager,
    ui::{list::StatefulList, toast::Urgency},
};
use anyhow::Result;
use nmrs::{Network, WifiDevice};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};

pub enum AppEvent {
    Toast(Option<Cow<'static, str>>, Cow<'static, str>, Urgency, Option<Duration>),
    Refresh,
}

pub struct App {
    pub should_quit: bool,
@@ -9,10 +20,16 @@
    pub known_networks: StatefulList<Network>,
    pub available_networks: StatefulList<Network>,
    pub devices: StatefulList<WifiDevice>,

    pub event_sender: UnboundedSender<AppEvent>,
    pub event_receiver: UnboundedReceiver<AppEvent>,
}

impl App {
    pub async fn new(mut network_manager: NetworkManager) -> Result<Self> {
    pub async fn new() -> Result<Self> {
        let (event_sender, event_receiver) = mpsc::unbounded_channel::<AppEvent>();
        let mut network_manager = NetworkManager::new(event_sender.clone()).await?;

        let device_list = network_manager.get_devices().await.unwrap_or_default();
        let (known_networks_list, available_networks_list) =
            network_manager.networks_list().await?;
@@ -24,6 +41,8 @@
            known_networks: StatefulList::with_items(known_networks_list),
            available_networks: StatefulList::with_items(available_networks_list),
            devices: StatefulList::with_items(device_list),
            event_sender,
            event_receiver,
        })
    }

diff --git a/src/events.rs b/src/events.rs
index 4358a4e..85d5fb0 100644
--- a/src/events.rs
+++ b/src/events.rs
@@ -1,20 +1,26 @@
use anyhow::{Ok, Result};
use crossterm::event::{KeyCode, KeyEvent};
use nmrs::WifiSecurity;
use tokio::sync::mpsc::UnboundedSender;

use crate::{
    app::App,
    app::{App, AppEvent},
    tui::{Selected, Tabs, Tui},
    ui::input::InputMode,
    ui::{input::InputMode, toast::Urgency},
};

pub async fn handle_events(app: &mut App, tui: &mut Tui, key: KeyEvent) -> Result<()> {
pub async fn handle_events(
    app: &mut App,
    tui: &mut Tui,
    key: KeyEvent,
    event_sender: UnboundedSender<AppEvent>,
) -> Result<()> {
    match tui.input.mode {
        InputMode::Normal => match key.code {
            KeyCode::Char('q') => app.quit(),

            // Navigation
            KeyCode::Tab | KeyCode::Char('l') => {
            KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right => {
                tui.active_tab = match tui.active_tab {
                    Tabs::KnownNetworks => Tabs::AvailableNetworks,
                    Tabs::AvailableNetworks => Tabs::Devices,
@@ -22,7 +28,7 @@
                };
                tui.update_selected(app);
            }
            KeyCode::BackTab | KeyCode::Char('h') => {
            KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left => {
                tui.active_tab = match tui.active_tab {
                    Tabs::KnownNetworks => Tabs::Devices,
                    Tabs::AvailableNetworks => Tabs::KnownNetworks,
@@ -58,7 +64,7 @@
                    {
                        app.network_manager
                            .connect(&net.ssid, None, WifiSecurity::Open)
                            .await?;
                            .await;
                        app.known_networks.state.select_first();
                        tui.update_selected(app);
                    }
@@ -67,7 +73,8 @@
                    if let Some(Selected::Network(net)) = &tui.selected
                        && net.is_psk
                    {
                        tui.input.mode = InputMode::Editing
                        tui.input.mode = InputMode::Editing;
                        tui.scan = false;
                    }
                }
                Tabs::Devices => {}
@@ -76,15 +83,23 @@
                if tui.active_tab == Tabs::KnownNetworks
                    && let Some(Selected::Network(net)) = &tui.selected
                {
                    let _ = app.event_sender.send(AppEvent::Refresh);
                    app.network_manager.forget(&net.ssid).await?;
                    tui.update_selected(app);
                    // tui.update_selected(app);
                }
            }
            _ => {}
        },
        InputMode::Editing => match key.code {
            KeyCode::Enter => {
                tui.input.mode = InputMode::Normal;
                if let Some(Selected::Network(net)) = &tui.selected {
                    let _ = event_sender.send(AppEvent::Toast(
                        None,
                        format!("Connecting to {}...", net.ssid).into(),
                        Urgency::Normal,
                        None,
                    ));
                    app.network_manager
                        .connect(
                            &net.ssid,
@@ -93,23 +108,24 @@
                                psk: tui.input.value.clone(),
                            },
                        )
                        .await?;
                    tui.input.mode = InputMode::Normal;
                        .await;
                    tui.input.value.clear();
                    tui.input.reset_cursor();
                    app.available_networks.next();
                    tui.update_selected(app);
                    tui.scan = true;
                }
            }
            KeyCode::Tab => tui.input.hidden_password = !tui.input.hidden_password,
            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(),
            KeyCode::Esc => {
                tui.input.mode = InputMode::Normal;
                tui.input.value.clear();
                tui.input.reset_cursor();
            }
            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(),
            _ => {}
        },
    }
diff --git a/src/main.rs b/src/main.rs
index 1d2706e..5581958 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -13,14 +13,11 @@
use app::App;
use tui::Tui;

use crate::network_manager::NetworkManager;

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize
    logger::init()?;
    let network_manager = NetworkManager::new().await?;
    let mut app = App::new(network_manager).await?;
    let mut app = App::new().await?;
    let mut tui = Tui::new(&mut app)?;

    // Start TUI
diff --git a/src/network_manager.rs b/src/network_manager.rs
index 7278f63..c84daa8 100644
--- a/src/network_manager.rs
+++ b/src/network_manager.rs
@@ -1,16 +1,20 @@
use anyhow::{Ok, Result};
use nmrs::{ConnectionError, Network, SavedConnection, WifiDevice, WifiSecurity};
use tokio::sync::mpsc::UnboundedSender;

#[derive()]
use crate::{app::AppEvent, ui::toast::Urgency};

#[derive(Clone)]
pub struct NetworkManager {
    pub nmrs: nmrs::NetworkManager,
    pub event_sender: UnboundedSender<AppEvent>,
    pub current_connection: Option<Network>,
    pub devices: Vec<WifiDevice>,
    pub enabled: bool,
}

impl NetworkManager {
    pub async fn new() -> anyhow::Result<Self> {
    pub async fn new(event_sender: UnboundedSender<AppEvent>) -> anyhow::Result<Self> {
        let nmrs = nmrs::NetworkManager::new().await?;
        let current_connection = nmrs.current_network().await?;

@@ -20,6 +24,7 @@

        Ok(Self {
            nmrs,
            event_sender,
            current_connection,
            devices,
            enabled,
@@ -63,42 +68,72 @@
        self.nmrs.forget(ssid).await
    }

    // TODO: add toast msg, send a signal or somthing like that.
    pub async fn connect(
        &mut self,
        ssid: &str,
        interface: Option<&str>,
        credentials: WifiSecurity,
    ) -> Result<()> {
        match self
            .nmrs
            .connect(ssid, interface, credentials)
            .await
        {
    ) {
        match self.nmrs.connect(ssid, interface, credentials).await {
            std::result::Result::Ok(_) => {
                debug!("Connected!");
                Ok(())
                let msg = "Connected!";
                info!("{}", msg);
                let _ = self.event_sender.send(AppEvent::Toast(
                    None,
                    msg.into(),
                    Urgency::Success,
                    None,
                ));
            }
            Err(ConnectionError::NotFound) => {
                warn!("Network not visible — is it in range?");
                Ok(())
                let msg = "Network not visible — is it in range?";
                error!("{}", msg);
                let _ = self.event_sender.send(AppEvent::Toast(
                    None,
                    msg.into(),
                    Urgency::Critical,
                    None,
                ));
            }
            Err(ConnectionError::AuthFailed) => {
                self.forget(ssid).await?;
                warn!("Wrong password");
                Ok(())
                let _ = self.forget(ssid).await;
                let msg = "Wrong password!";
                error!("{}", msg);
                let _ = self.event_sender.send(AppEvent::Toast(
                    None,
                    msg.into(),
                    Urgency::Critical,
                    None,
                ));
            }
            Err(ConnectionError::Timeout) => {
                error!("Connection timed out — try increasing the timeout");
                Ok(())
                let msg = "Connection timed out — try increasing the timeout";
                error!("{}", msg);
                let _ = self.event_sender.send(AppEvent::Toast(
                    None,
                    msg.into(),
                    Urgency::Critical,
                    None,
                ));
            }
            Err(ConnectionError::DhcpFailed) => {
                error!("Failed to get an IP address");
                Ok(())
                let msg = "Failed to get an IP address";
                error!("{}", msg);
                let _ = self.event_sender.send(AppEvent::Toast(
                    None,
                    msg.into(),
                    Urgency::Critical,
                    None,
                ));
            }
            Err(e) => {
                let _ = self.event_sender.send(AppEvent::Toast(
                    None,
                    "Connection failed - check logs".into(),
                    Urgency::Critical,
                    None,
                ));
                error!("Connection failed: {}", e);
                Ok(())
            }
        }
    }
diff --git a/src/tui.rs b/src/tui.rs
index 5f071de..f43b590 100644
--- a/src/tui.rs
+++ b/src/tui.rs
@@ -10,16 +10,19 @@
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout},
};
use std::{io::stdout, time::Duration};
use std::{
    io::stdout,
    time::{self, Duration},
};

use crate::{
    app::App,
    app::{App, AppEvent},
    events,
    ui::{
        Urgency,
        help,
        input::{Input, InputMode},
        popup, table,
        toast::{self, Toast},
    },
};

@@ -42,6 +45,9 @@
    pub input: Input,
    pub active_tab: Tabs,
    pub selected: Option<Selected>,
    pub toasts: Vec<Toast>,

    pub scan: bool,
}

impl Tui {
@@ -63,8 +69,11 @@
            terminal,

            input: Input::new(),
            selected: None,
            active_tab: Tabs::KnownNetworks,
            selected: None,
            toasts: Vec::new(),

            scan: true,
        })
    }

@@ -93,18 +102,30 @@
        };
    }

    // TODO: whats is the diffrence between std time and tokio
    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);
        let mut last_tick = time::Instant::now();
        let mut rescan_timer = Duration::from_secs(10);
        self.update_selected(app);

        while !app.should_quit {
            if last_tick.elapsed() >= tick_rate {
                if let Err(e) = app.refresh_networks().await {
                    eprintln!("scan error: {:?}", e);
                }
                last_tick = tokio::time::Instant::now();
            let now = time::Instant::now();
            let delta = now.saturating_duration_since(last_tick);
            last_tick = now;

            // Toast duration timer
            self.toasts.iter_mut().for_each(|toast| {
                toast.duration = toast.duration.saturating_sub(delta);
            });
            self.toasts.retain(|toast| !toast.duration.is_zero());

            // Rescan timer
            rescan_timer = rescan_timer.saturating_sub(delta);
            if rescan_timer.is_zero() {
                app.event_sender.send(AppEvent::Refresh)?;
                rescan_timer = Duration::from_secs(10);
            }

            self.terminal.draw(|f| {
                let size = f.area();

@@ -116,9 +137,9 @@
                let body_chunks = Layout::new(
                    Direction::Vertical,
                    [
                        Constraint::Percentage(40),
                        Constraint::Percentage(40),
                        Constraint::Percentage(20),
                        Constraint::Percentage(45),
                        Constraint::Percentage(45),
                        Constraint::Percentage(10),
                        Constraint::Length(1),
                    ],
                )
@@ -130,14 +151,29 @@
                help::draw(f, body_chunks[3], &self.active_tab);

                if self.input.mode == InputMode::Editing {
                    popup::draw_auth(f, &self.input, &self.selected);
                    popup::draw_auth(f, &self.input, &self.selected, self.input.hidden_password);
                }
                toast::draw(f, &self.toasts);
            })?;

            while let std::result::Result::Ok(event) = app.event_receiver.try_recv() {
                match event {
                    AppEvent::Toast(title, msg, urgency, duration) => {
                        self.toasts.push(Toast::new(title, msg, urgency, duration));
                    }
                    AppEvent::Refresh => {
                        if self.scan {
                            app.refresh_networks().await?;
                            self.update_selected(app);
                        }
                    }
                }
            }

            if event::poll(std::time::Duration::from_millis(200))?
                && let Event::Key(key) = event::read()?
            {
                events::handle_events(app, self, key).await?;
                events::handle_events(app, self, key, app.event_sender.clone()).await?;
            }
        }

@@ -148,9 +184,7 @@
    // terminal cleanup
    fn cleanup(&mut self) -> Result<()> {
        disable_raw_mode()?;
        self.terminal
            .backend_mut()
            .execute(LeaveAlternateScreen)?;
        self.terminal.backend_mut().execute(LeaveAlternateScreen)?;
        self.terminal.show_cursor()?;
        Ok(())
    }
diff --git a/src/ui/input.rs b/src/ui/input.rs
index f39e582..6a20fa3 100644
--- a/src/ui/input.rs
+++ b/src/ui/input.rs
@@ -7,6 +7,7 @@
pub struct Input {
    pub mode: InputMode,
    pub value: String,
    pub hidden_password: bool,
    // cursor postion x.
    pub cx: usize,
}
@@ -16,6 +17,7 @@
        Self {
            mode: InputMode::Normal,
            value: String::new(),
            hidden_password: true,
            cx: 0,
        }
    }
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index ef1eec2..75ad7aa 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -5,6 +5,7 @@
pub mod list;
pub mod popup;
pub mod table;
pub mod toast;

#[allow(dead_code)]
#[derive(Default)]
@@ -23,12 +24,6 @@
    RightBottom,
}

pub enum Urgency {
    Success,
    Warning,
    Critical,
}

#[derive(Default)]
pub struct Gaps {
    top: u16,
@@ -40,18 +35,25 @@
// calculate area position
pub fn position_rect(
    area: Rect,
    width: u16,
    height: u16,
    mut width: u16,
    mut height: u16,
    position: Position,
    gaps: Option<Gaps>,
    gaps: Gaps,
) -> Rect {
    let gaps = gaps.unwrap_or_default();
    // 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,
        Position::LeftTop | Position::LeftCenter | Position::LeftBottom => {
            0_u16.saturating_add(gaps.left).saturating_sub(gaps.right)
        }

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

        Position::RightTop | Position::RightCenter | Position::RightBottom => area
            .width
            .saturating_sub(width)
@@ -60,12 +62,16 @@
    };

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

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

        Position::LeftBottom | Position::Bottom | Position::RightBottom => area
            .height
            .saturating_sub(height)
diff --git a/src/ui/popup.rs b/src/ui/popup.rs
index 73b11ec..38caf98 100644
--- a/src/ui/popup.rs
+++ b/src/ui/popup.rs
@@ -1,14 +1,14 @@
use nmrs::{Network, WifiSecurity};
use ratatui::{
    Frame,
    layout::{self, Rect},
    style::{Color, Style, Stylize},
    widgets::{Block, Paragraph},
    layout::{self, Alignment, Constraint, Layout, Rect},
    style::{Color, Style},
    text::{Line, Span},
    widgets::{self, Block, Paragraph},
};

use crate::{
    tui::Selected,
    ui::{self, Gaps, Position, Urgency, input::Input},
    ui::{self, Gaps, Position, input::Input},
};

#[derive(Default)]
@@ -23,79 +23,67 @@
    pub position: Position,

    /// gaps of the popup.
    pub gaps: Option<Gaps>,

    /// dim the background.
    pub dim: Option<Color>,
    pub gaps: Gaps,
}

pub fn popup_area(f: &mut Frame, opt: Options) -> Rect {
    if opt.dim.is_some() {
        // Dim the background.
        let dimming_block = ratatui::widgets::Block::default().bg(opt.dim.unwrap_or_default());
        f.render_widget(dimming_block, f.area());
    }

    let area = ui::position_rect(f.area(), opt.width, opt.height, opt.position, opt.gaps);
    f.render_widget(ratatui::widgets::Clear, area); // Clear the table behind it
    f.render_widget(widgets::Clear, area); // Clear the area behind it
    area
}

// TODO: draw toast
pub fn draw_toast(f: &mut Frame, msg: &str, urgency: Urgency) {
    let area = popup_area(
pub fn draw_auth(f: &mut Frame, input: &Input, selected: &Option<Selected>, hidden_password: bool) {
    let popup_area = popup_area(
        f,
        Options {
            width: 30,
            height: 3,
            position: Position::RightBottom,
            gaps: Some(Gaps {
                bottom: 1,
                right: 1,
                ..Default::default()
            }),
            ..Default::default()
        },
    );

    let border_style = match urgency {
        Urgency::Success => Style::new().green(),
        Urgency::Warning => Style::new().yellow(),
        Urgency::Critical => Style::new().red(),
    };
    let block = Block::bordered().border_style(border_style);
    f.render_widget(Paragraph::new(msg).block(block), area);
}

pub fn draw_auth(f: &mut Frame, input: &Input, selected: &Option<Selected> ) {
    let input_area = popup_area(
        f,
        Options {
            width: 30,
            height: 3,
            width: 60,
            height: 7,
            position: Position::Center,
            dim: Some(Color::Black),
            ..Default::default()
        },
    );


    if let Some(Selected::Network(net)) = selected {
        let block = Block::bordered()
            .title(format!(" Password for {} ", net.ssid))
            .border_style(Style::default().fg(Color::Yellow));

        // Hide password with asterisks for security
        let display_pass: String = input.value.chars().map(|_| '*').collect();
        let text = Paragraph::new(display_pass).block(block);
        f.render_widget(text, input_area);
        let block = Block::bordered().border_style(Style::default().fg(Color::Yellow).bold());

        let title = Line::from(vec![
            Span::raw("Enter the password for "),
            Span::styled(&net.ssid, Style::new().bold()),
        ]).alignment(Alignment::Center);

        let title_widget = Paragraph::new(title).block(block);
        f.render_widget(title_widget, popup_area);

        let input_area = Rect::new(
            popup_area.x + 1,
            popup_area.y + 3,
            popup_area.width.saturating_sub(2),
            1,
        );

        let input_chunks = Layout::horizontal([
            Constraint::Min(0),    // Password input
            Constraint::Length(4), // eye icon
        ])
        .split(input_area);

        let (password, icon): (String, &'static str) = if hidden_password {
            (input.value.chars().map(|_| '*').collect(), " 󰈉  ")
        } else {
            (input.value.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]);

        let cx = input_chunks[0].x + input.cx as u16;
        let cx_max = input_chunks[0].x + input_chunks[0].width.saturating_sub(1) as u16;
        f.set_cursor_position(layout::Position::new(
            // Draw the cursor at the current position in the input field.
            // Add 1 to position so it dont be on the border, min is forest the cursor can go mines
            // the borders
            (input_area.x + input.cx as u16 + 1).min(input_area.x + input_area.width.saturating_sub(2)),
            // Move one line down, from the border to the input line
            input_area.y + 1,
            cx.min(cx_max),
            input_chunks[0].y,
        ))
    }
}
diff --git a/src/ui/table.rs b/src/ui/table.rs
index 7950d4d..04ebebb 100644
--- a/src/ui/table.rs
+++ b/src/ui/table.rs
@@ -23,7 +23,7 @@
        Style::new()
    };
    let row_style = if is_active {
        Style::new().on_blue().black()
        Style::new().on_dark_gray()
    } else {
        Style::new()
    };
@@ -124,6 +124,7 @@
    );
}

// TODO: make constraint long as it need
pub fn draw_available_network(
    f: &mut Frame<'_>,
    body_chunks: &Rc<[Rect]>,
@@ -137,7 +138,15 @@
        .map(|net| -> Row<'_> {
            Row::new(vec![
                Cell::from(net.ssid.clone()),
                Cell::from(if net.secured { "Secured" } else { "Open" }),
                Cell::from(if net.is_psk {
                    "psk"
                } else if net.is_eap {
                    "Enterprise"
                } else if !net.secured {
                    "Open"
                } else {
                    "Unknown"
                }),
                Cell::from(format!("{}%", net.strength.unwrap_or(0))),
            ])
        })
@@ -160,6 +169,7 @@
    );
}

// TODO: Add cells
pub fn draw_devices(f: &mut Frame<'_>, body_chunks: &Rc<[Rect]>, app: &mut App, active_tab: &Tabs) {
    let rows: Vec<Row> = app
        .devices
diff --git a/src/ui/toast.rs b/src/ui/toast.rs
new file mode 100644
index 0000000..0a1ba0c 100644
--- /dev/null
+++ b/src/ui/toast.rs
@@ -1,0 +1,98 @@
use std::{borrow::Cow, time::Duration};

use ratatui::{
    Frame, layout::Alignment, style::Style, text::Line, widgets::{Block, Paragraph}
};

use crate::ui::{
    Gaps, Position,
    popup::{self, Options},
};

#[derive(Clone, Copy, PartialEq)]
pub enum Urgency {
    Normal,
    Success,
    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,
}

impl Toast {
    pub fn new<S>(title: Option<S>, msg: S, urgency: Urgency, duration: Option<Duration>) -> Self
    where
        S: 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 title_unwraped: 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(),
            },
        };

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

pub fn draw(f: &mut Frame, toasts: &[Toast]) {
    for (index, toast) in toasts.iter().enumerate() {
        let area = popup::popup_area(
            f,
            Options {
                width: 3 + toast.msg.chars().count() as u16,
                height: 4,
                position: Position::RightTop,
                gaps: Gaps {
                    top: 1 + (index as u16 * 4),
                    right: 1,
                    ..Default::default()
                },
            },
        );

        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 title = Line::raw(toast.title.as_ref()).style(title_style.bold()).alignment(Alignment::Center);
        let msg = Line::raw(toast.msg.as_ref());

        let block = Block::bordered().border_style(border_style).border_type(ratatui::widgets::BorderType::Thick);
        f.render_widget(Paragraph::new(vec![title, msg]).block(block), area);
    }
}