Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

feat: implement reusable UI overlay module for modals, pickers, and notifications

Samir Hossainsb6be99bd5b59
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 7caa349..e66cdf5 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -13,6 +13,7 @@ use crate::providers::{
use crate::tui::{
action::Action,
event::EventHandler,
+ overlay::NotificationKind,
state::{AppState, InputMode, Screen, SearchResult},
theme::Theme,
};
@@ -344,11 +345,18 @@ impl App {
let Some(link) = self.get_selected_link() else {
if self.state.is_fetching_streams {
self.state.is_waiting_for_download_stream = true;
- self.state.toast_message = Some("Waiting for stream details...".into());
+ self.state.notify(
+ NotificationKind::Info,
+ "Preparing download",
+ "Waiting for stream details.",
+ );
} else {
- self.state.toast_message = Some("No downloadable stream selected.".into());
+ self.state.notify(
+ NotificationKind::Warning,
+ "Download unavailable",
+ "Select a downloadable stream first.",
+ );
}
- self.state.toast_timer = 120;
return;
};
@@ -421,8 +429,11 @@ impl App {
self.state
.cancel_download
.store(false, std::sync::atomic::Ordering::SeqCst);
- self.state.toast_message = Some("Download started. Partial data will be preserved.".into());
- self.state.toast_timer = 80;
+ self.state.notify(
+ NotificationKind::Info,
+ "Download started",
+ "Partial data will be preserved.",
+ );
let cancel = self.state.cancel_download.clone();
let sender = self.action_sender.clone();
@@ -610,12 +621,9 @@ impl App {
let mut needs_redraw = (self.state.is_loading && self.state.tick_count % 5 == 0)
|| self.state.tick_count < 15;
self.state.tick_count = self.state.tick_count.wrapping_add(1);
- if self.state.toast_timer > 0 {
+ if !self.state.notifications.is_empty() {
needs_redraw = true;
- self.state.toast_timer -= 1;
- if self.state.toast_timer == 0 {
- self.state.toast_message = None;
- }
+ self.state.expire_notifications();
}
if self.state.status_timer > 0 {
needs_redraw = true;
@@ -1257,6 +1265,14 @@ impl App {
Action::ToggleHelp => {
if matches!(self.state.active_screen, Screen::Home | Screen::Details) {
self.state.show_help = !self.state.show_help;
+ if self.state.show_help {
+ self.state.tv_config_popup = false;
+ self.state.player_picker_popup = false;
+ self.state.subtitle_popup = false;
+ self.state.is_download_subtitle_popup = false;
+ self.state.show_season_download_confirm = false;
+ self.state.show_episode_download_confirm = false;
+ }
}
}
Action::ToggleTvMode => {
@@ -1308,6 +1324,10 @@ impl App {
}
Action::ShowTvWizard => {
if self.state.is_tv_mode {
+ self.state.show_help = false;
+ self.state.player_picker_popup = false;
+ self.state.subtitle_popup = false;
+ self.state.is_download_subtitle_popup = false;
self.state.tv_config_popup = true;
self.state.input_mode = crate::tui::state::InputMode::Normal;
}
@@ -1599,20 +1619,15 @@ impl App {
self.persist_config();
self.state.search_query.clear();
self.state.input_mode = InputMode::Normal;
- self.state.toast_message = Some(format!(
- "{} Auto Update is now {}",
- if self.state.basic_terminal {
- "[!]"
- } else {
- "!"
- },
+ self.state.notify(
+ NotificationKind::Info,
+ "Automatic updates",
if self.state.auto_update {
"Enabled"
} else {
"Disabled"
- }
- ));
- self.state.toast_timer = 50;
+ },
+ );
return None;
}
@@ -2885,8 +2900,11 @@ impl App {
Action::PlayStream(open_with) => {
if self.state.active_provider == ProviderKind::FourKHdHub {
if let Some(release) = self.get_selected_release() {
- self.state.toast_message = Some("Resolving selected mirror...".into());
- self.state.toast_timer = 80;
+ self.state.notify(
+ NotificationKind::Info,
+ "Preparing playback",
+ "Resolving the selected mirror.",
+ );
let client = self.fourk_client.clone();
let sender = self.action_sender.clone();
tokio::spawn(async move {
@@ -2928,15 +2946,11 @@ impl App {
let resource_id = self.get_selected_resource_id();
if let Some(rid) = resource_id {
- self.state.toast_message = Some(format!(
- "{} Fetching subtitles...",
- if self.state.basic_terminal {
- "[OK]"
- } else {
- "✓"
- }
- ));
- self.state.toast_timer = 40;
+ self.state.notify(
+ NotificationKind::Info,
+ "Preparing playback",
+ "Fetching subtitles.",
+ );
let client = self.client.clone();
let sender = self.action_sender.clone();
let link_clone = link.clone();
@@ -2988,6 +3002,9 @@ impl App {
}
if options.len() > 1 {
+ self.state.show_help = false;
+ self.state.player_picker_popup = false;
+ self.state.is_download_subtitle_popup = false;
self.state.subtitle_popup = true;
self.state.subtitle_list = options;
self.state.subtitle_list_state.select(Some(0));
@@ -3027,6 +3044,9 @@ impl App {
}
if options.len() > 1 {
+ self.state.show_help = false;
+ self.state.player_picker_popup = false;
+ self.state.subtitle_popup = false;
self.state.is_download_subtitle_popup = true;
self.state.subtitle_list = options;
self.state.subtitle_list_state.select(Some(0));
@@ -3038,15 +3058,11 @@ impl App {
let player = self.state.available_players.first().cloned();
match player {
None => {
- self.state.toast_message = Some(format!(
- "{} No media player found. Install mpv, IINA, or VLC.",
- if self.state.basic_terminal {
- "[X]"
- } else {
- "✗"
- }
- ));
- self.state.toast_timer = 150;
+ self.state.notify(
+ NotificationKind::Error,
+ "Player unavailable",
+ "Install mpv, IINA, or VLC.",
+ );
}
Some(kind) => {
let player_name = match kind {
@@ -3054,16 +3070,11 @@ impl App {
crate::tui::state::PlayerKind::Iina => "IINA",
crate::tui::state::PlayerKind::Vlc => "VLC",
};
- self.state.toast_message = Some(format!(
- "{} Launching {}...",
- if self.state.basic_terminal {
- "[OK]"
- } else {
- "✓"
- },
- player_name
- ));
- self.state.toast_timer = 40;
+ self.state.notify(
+ NotificationKind::Info,
+ "Opening player",
+ format!("Launching {player_name}."),
+ );
self.action_sender
.send(Action::LaunchPlayer(kind, link, subtitle_url))
@@ -3083,7 +3094,7 @@ impl App {
return None;
}
self.state.show_episode_download_confirm = true;
- self.state.episode_download_confirm_yes_selected = true;
+ self.state.episode_download_confirm_yes_selected = false;
}
Action::ConfirmDownloadEpisode => {
@@ -3100,15 +3111,11 @@ impl App {
let resource_id = self.get_selected_resource_id();
if let Some(rid) = resource_id {
- self.state.toast_message = Some(format!(
- "{} Fetching subtitles...",
- if self.state.basic_terminal {
- "[OK]"
- } else {
- "✓"
- }
- ));
- self.state.toast_timer = 40;
+ self.state.notify(
+ NotificationKind::Info,
+ "Preparing download",
+ "Fetching subtitles.",
+ );
let client = self.client.clone();
let sender = self.action_sender.clone();
tokio::spawn(async move {
@@ -3131,7 +3138,7 @@ impl App {
return None;
}
self.state.show_season_download_confirm = true;
- self.state.season_download_confirm_yes_selected = true;
+ self.state.season_download_confirm_yes_selected = false;
}
Action::ConfirmDownloadSeason => {
@@ -3174,11 +3181,11 @@ impl App {
let total = self.state.download_queue_total;
let num = total - remaining;
- self.state.toast_message = Some(format!(
- "Preparing S{:02}E{:02} ({}/{})",
- season, episode, num, total
- ));
- self.state.toast_timer = 60;
+ self.state.notify(
+ NotificationKind::Info,
+ "Preparing episode",
+ format!("S{season:02}E{episode:02} · {num}/{total}"),
+ );
let subject_id = self
.state
@@ -3205,11 +3212,11 @@ impl App {
self.action_sender.send(Action::DownloadStream(None)).ok();
} else if self.state.download_queue_total > 0 {
- self.state.toast_message = Some(format!(
- "Season download complete! ({} files)",
- self.state.download_queue_total
- ));
- self.state.toast_timer = 100;
+ self.state.notify(
+ NotificationKind::Success,
+ "Season downloaded",
+ format!("{} files completed.", self.state.download_queue_total),
+ );
self.state.download_queue_total = 0;
}
}
@@ -3392,11 +3399,15 @@ impl App {
}
Action::SetStatus(msg) => {
if msg.starts_with("Error:") {
- self.state.toast_message = Some(msg.clone());
- self.state.toast_timer = 180;
+ self.state.notify(
+ NotificationKind::Error,
+ "Operation failed",
+ msg.trim_start_matches("Error:").trim(),
+ );
+ } else {
+ self.state.status_message = msg;
+ self.state.status_timer = 150;
}
- self.state.status_message = msg;
- self.state.status_timer = 150;
}
Action::InitStreamPool(subject_id) => {
let pool = crate::tui::state::SubjectStreamPool {
@@ -3929,8 +3940,11 @@ impl App {
Action::DownloadCompleted(path) => {
self.state.download_progress = Some(100.0);
self.state.download_status = Some("Completed".into());
- self.state.toast_message = Some(format!("Downloaded to {path}"));
- self.state.toast_timer = 120;
+ self.state.notify(
+ NotificationKind::Success,
+ "Download complete",
+ format!("Saved to {path}"),
+ );
let sender = self.action_sender.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
@@ -3942,22 +3956,22 @@ impl App {
self.state.download_status = None;
self.state.download_queue.clear();
self.state.download_queue_total = 0;
- self.state.toast_message =
- Some(format!("Download failed; partial preserved: {error}"));
- self.state.toast_timer = 240;
- self.state.status_message =
- format!("Download failed; retry to resume. Reason: {error}");
- self.state.status_timer = 240;
+ self.state.notify(
+ NotificationKind::Error,
+ "Download failed",
+ format!("Partial file preserved. {error}"),
+ );
}
Action::DownloadPaused(path) => {
self.state.download_progress = None;
self.state.download_status = None;
self.state.download_queue.clear();
self.state.download_queue_total = 0;
- self.state.toast_message = Some(format!(
- "Download paused. Start again to resume: {path}.part"
- ));
- self.state.toast_timer = 240;
+ self.state.notify(
+ NotificationKind::Warning,
+ "Download paused",
+ format!("Start again to resume {path}.part"),
+ );
}
Action::ClearDownload => {
self.state.download_progress = None;
@@ -3965,11 +3979,11 @@ impl App {
if !self.state.download_queue.is_empty() {
self.action_sender.send(Action::ProcessDownloadQueue).ok();
} else if self.state.download_queue_total > 0 {
- self.state.toast_message = Some(format!(
- "Season download complete! ({} files)",
- self.state.download_queue_total
- ));
- self.state.toast_timer = 120;
+ self.state.notify(
+ NotificationKind::Success,
+ "Season downloaded",
+ format!("{} files completed.", self.state.download_queue_total),
+ );
self.state.download_queue_total = 0;
}
}
@@ -3978,15 +3992,11 @@ impl App {
.cancel_download
.store(true, std::sync::atomic::Ordering::SeqCst);
self.state.download_status = Some("Cancelling...".to_string());
- self.state.toast_message = Some(format!(
- "{} Cancelling download...",
- if self.state.basic_terminal {
- "[X]"
- } else {
- "✗"
- }
- ));
- self.state.toast_timer = 40;
+ self.state.notify(
+ NotificationKind::Warning,
+ "Cancelling download",
+ "Partial data will be preserved.",
+ );
}
Action::PlayersDetected(players) => {
@@ -3999,6 +4009,8 @@ impl App {
self.state.status_timer = 150;
return None;
}
+ self.state.show_help = false;
+ self.state.tv_config_popup = false;
self.state.player_picker_popup = true;
self.state.player_picker_playback = Some(source);
self.state.player_picker_link = None;
@@ -4008,17 +4020,15 @@ impl App {
}
Action::ShowPlayerPicker(link, subtitle) => {
if self.state.available_players.is_empty() {
- self.state.toast_message = Some(format!(
- "{} No media player found. Install mpv, IINA, or VLC.",
- if self.state.basic_terminal {
- "[X]"
- } else {
- "✗"
- }
- ));
- self.state.toast_timer = 150;
+ self.state.notify(
+ NotificationKind::Error,
+ "Player unavailable",
+ "Install mpv, IINA, or VLC.",
+ );
return None;
}
+ self.state.show_help = false;
+ self.state.tv_config_popup = false;
self.state.player_picker_popup = true;
self.state.player_picker_playback = None;
self.state.player_picker_link = Some(link);
@@ -4120,9 +4130,11 @@ impl App {
if version == "none" {
if self.state.active_screen == Screen::Startup {
self.state.active_screen = Screen::Home;
- self.state.toast_message =
- Some("You are on the latest version!".to_string());
- self.state.toast_timer = 40;
+ self.state.notify(
+ NotificationKind::Success,
+ "Up to date",
+ "You are using the latest version.",
+ );
}
} else {
self.state.update_available = Some(version);
@@ -4133,14 +4145,11 @@ impl App {
}
Err(error) => {
self.state.active_screen = Screen::Home;
- self.state.toast_message = Some(format!(
- "Update available, but automatic install needs permission: {error}"
- ));
- self.state.toast_timer = 300;
- self.state.status_message =
- "Run the platform installer to update this installation."
- .into();
- self.state.status_timer = 300;
+ self.state.notify(
+ NotificationKind::Warning,
+ "Update needs permission",
+ error,
+ );
}
}
}
@@ -4187,11 +4196,8 @@ impl App {
self.state.updater_progress = None;
self.state.updater_status = None;
self.state.active_screen = Screen::Home;
- self.state.toast_message = Some(format!("Update failed: {error}"));
- self.state.toast_timer = 300;
- self.state.status_message =
- "Automatic update failed. See the message above or reinstall manually.".into();
- self.state.status_timer = 300;
+ self.state
+ .notify(NotificationKind::Error, "Update failed", error);
}
}
None
@@ -4298,37 +4304,12 @@ impl App {
}
}
- if let Some(msg) = &self.state.toast_message {
- use ratatui::layout::{Constraint, Direction, Layout};
-
- use ratatui::widgets::Paragraph;
-
- let inner_area = area.inner(ratatui::layout::Margin {
- vertical: 1,
- horizontal: 2,
- });
- let chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([Constraint::Length(1), Constraint::Min(0)])
- .split(inner_area);
-
- let toast_area = Layout::default()
- .direction(Direction::Horizontal)
- .constraints([
- Constraint::Min(0),
- Constraint::Length(msg.chars().count() as u16 + 2),
- ])
- .split(chunks[0])[1];
-
- let color = if self.state.toast_timer < 10 {
- self.theme.muted
- } else {
- self.theme.success
- };
-
- let p = Paragraph::new(msg.clone())
- .style(color.add_modifier(ratatui::style::Modifier::BOLD));
- frame.render_widget(p, toast_area);
- }
+ crate::tui::overlay::notifications(
+ frame,
+ area,
+ &self.state.notifications,
+ &self.theme,
+ self.state.basic_terminal,
+ );
}
}
diff --git a/src/tui/mod.rs b/src/tui/mod.rs
index feec109..b68c4f1 100644
--- a/src/tui/mod.rs
+++ b/src/tui/mod.rs
@@ -2,6 +2,7 @@ pub mod action;
pub mod app;
pub mod event;
pub mod iptv_data;
+pub mod overlay;
pub mod player;
pub mod state;
pub mod terminal;
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
new file mode 100644
index 0000000..ec58614
--- /dev/null
+++ b/src/tui/overlay.rs
@@ -0,0 +1,381 @@
+use std::time::{Duration, Instant};
+
+use ratatui::{
+ Frame,
+ layout::{Alignment, Constraint, Layout, Rect},
+ style::{Modifier, Style},
+ text::{Line, Span},
+ widgets::{
+ Block, BorderType, Borders, List, ListItem, ListState, Paragraph, Scrollbar,
+ ScrollbarOrientation, ScrollbarState, Wrap,
+ },
+};
+
+use crate::tui::theme::Theme;
+
+const MAX_PICKER_ROWS: usize = 8;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NotificationKind {
+ Info,
+ Success,
+ Warning,
+ Error,
+}
+
+#[derive(Debug, Clone)]
+pub struct Notification {
+ pub kind: NotificationKind,
+ pub title: String,
+ pub message: String,
+ expires_at: Instant,
+}
+
+impl Notification {
+ pub fn new(
+ kind: NotificationKind,
+ title: impl Into<String>,
+ message: impl Into<String>,
+ ) -> Self {
+ let duration = match kind {
+ NotificationKind::Info => Duration::from_secs(4),
+ NotificationKind::Success => Duration::from_secs(5),
+ NotificationKind::Warning => Duration::from_secs(7),
+ NotificationKind::Error => Duration::from_secs(10),
+ };
+ Self {
+ kind,
+ title: title.into(),
+ message: message.into(),
+ expires_at: Instant::now() + duration,
+ }
+ }
+
+ pub fn expired(&self) -> bool {
+ Instant::now() >= self.expires_at
+ }
+}
+
+pub struct PickerSpec<'a> {
+ pub title: &'a str,
+ pub confirm_label: &'a str,
+ pub minimum_width: u16,
+}
+
+pub fn picker(
+ frame: &mut Frame,
+ area: Rect,
+ items: &[String],
+ state: &mut ListState,
+ spec: PickerSpec<'_>,
+ theme: &Theme,
+ basic_terminal: bool,
+) {
+ let selected = state
+ .selected()
+ .unwrap_or(0)
+ .min(items.len().saturating_sub(1));
+ let visible_rows = items.len().clamp(1, MAX_PICKER_ROWS);
+ let footer_width = crate::tui::text::width("[↑↓] Move [Enter] Download [Esc] Back");
+ let content_width = items
+ .iter()
+ .map(|item| crate::tui::text::width(item))
+ .max()
+ .unwrap_or(0)
+ .max(footer_width)
+ .saturating_add(4);
+ let popup = centered(
+ area,
+ content_width as u16,
+ visible_rows as u16 + 4,
+ spec.minimum_width,
+ 64,
+ );
+ clear_modal_area(frame, area, popup, theme);
+
+ let title = format!(
+ " {} · {}/{} ",
+ spec.title,
+ selected.saturating_add(1),
+ items.len().max(1)
+ );
+ let block = Block::default()
+ .title(title)
+ .title_style(theme.title)
+ .borders(Borders::ALL)
+ .border_type(if basic_terminal {
+ BorderType::Plain
+ } else {
+ BorderType::Rounded
+ })
+ .border_style(theme.border_focus);
+ let inner = block.inner(popup);
+ frame.render_widget(block, popup);
+
+ let sections = Layout::vertical([Constraint::Min(1), Constraint::Length(2)]).split(inner);
+ let list_items = items
+ .iter()
+ .map(|item| ListItem::new(item.clone()).style(theme.text))
+ .collect::<Vec<_>>();
+ let list = List::new(list_items)
+ .highlight_style(
+ theme
+ .highlight
+ .add_modifier(Modifier::BOLD | Modifier::REVERSED),
+ )
+ .highlight_symbol(if basic_terminal { "> " } else { "▌ " });
+ frame.render_stateful_widget(list, sections[0], state);
+
+ if items.len() > visible_rows {
+ let mut scrollbar_state = ScrollbarState::new(items.len())
+ .viewport_content_length(visible_rows)
+ .position(selected);
+ let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
+ .thumb_style(theme.accent)
+ .track_style(theme.muted)
+ .begin_symbol(Some("▲"))
+ .end_symbol(Some("▼"));
+ frame.render_stateful_widget(scrollbar, sections[0], &mut scrollbar_state);
+ }
+
+ let confirm_label = if sections[1].width < 40 && spec.confirm_label == "Download" {
+ "Save"
+ } else {
+ spec.confirm_label
+ };
+ let footer = Line::from(vec![
+ key_hint("↑↓", "Move", theme),
+ Span::raw(" "),
+ key_hint("Enter", confirm_label, theme),
+ Span::raw(" "),
+ key_hint("Esc", "Back", theme),
+ ]);
+ frame.render_widget(
+ Paragraph::new(footer).alignment(Alignment::Center).block(
+ Block::default()
+ .borders(Borders::TOP)
+ .border_style(theme.muted),
+ ),
+ sections[1],
+ );
+}
+
+pub fn confirmation(
+ frame: &mut Frame,
+ area: Rect,
+ title: &str,
+ summary: &[Line<'_>],
+ confirm_selected: bool,
+ theme: &Theme,
+ basic_terminal: bool,
+) {
+ let content_width = summary.iter().map(Line::width).max().unwrap_or(0).max(36);
+ let popup = centered(
+ area,
+ content_width.saturating_add(4) as u16,
+ summary.len() as u16 + 4,
+ 36,
+ 64,
+ );
+ clear_modal_area(frame, area, popup, theme);
+
+ let block = Block::default()
+ .title(format!(" {title} "))
+ .title_style(theme.title)
+ .borders(Borders::ALL)
+ .border_type(if basic_terminal {
+ BorderType::Plain
+ } else {
+ BorderType::Rounded
+ })
+ .border_style(theme.border_focus);
+ let inner = block.inner(popup);
+ frame.render_widget(block, popup);
+ let sections = Layout::vertical([
+ Constraint::Length(summary.len() as u16),
+ Constraint::Length(1),
+ Constraint::Length(1),
+ ])
+ .split(inner);
+ frame.render_widget(
+ Paragraph::new(summary.to_vec()).alignment(Alignment::Center),
+ sections[0],
+ );
+
+ let selected_style = theme
+ .highlight
+ .add_modifier(Modifier::BOLD | Modifier::REVERSED);
+ let actions = Line::from(vec![
+ Span::styled(
+ " Download ",
+ if confirm_selected {
+ selected_style
+ } else {
+ theme.text_dim
+ },
+ ),
+ Span::raw(" "),
+ Span::styled(
+ " Cancel ",
+ if confirm_selected {
+ theme.text_dim
+ } else {
+ selected_style
+ },
+ ),
+ ]);
+ frame.render_widget(
+ Paragraph::new(actions).alignment(Alignment::Center),
+ sections[1],
+ );
+ let footer = if sections[2].width < 44 {
+ Line::from(vec![
+ key_hint("←→", "Choose", theme),
+ Span::raw(" "),
+ key_hint("Enter", "OK", theme),
+ Span::raw(" "),
+ key_hint("Esc", "Back", theme),
+ ])
+ } else {
+ Line::from(vec![
+ key_hint("←→", "Choose", theme),
+ Span::raw(" "),
+ key_hint("Enter", "Confirm", theme),
+ Span::raw(" "),
+ key_hint("Esc", "Back", theme),
+ ])
+ };
+ frame.render_widget(
+ Paragraph::new(footer).alignment(Alignment::Center),
+ sections[2],
+ );
+}
+
+pub fn notifications(
+ frame: &mut Frame,
+ area: Rect,
+ notifications: &std::collections::VecDeque<Notification>,
+ theme: &Theme,
+ basic_terminal: bool,
+) {
+ let mut y = area.y.saturating_add(1);
+ for notification in notifications.iter().rev().take(3) {
+ let message = middle_truncate(&notification.message, 48);
+ let title_width = crate::tui::text::width(&notification.title).saturating_add(6);
+ let message_width = crate::tui::text::width(&message);
+ let width = title_width
+ .max(message_width.saturating_add(4))
+ .clamp(24, 52)
+ .min(area.width.saturating_sub(4) as usize) as u16;
+ if width < 4 || y.saturating_add(3) > area.bottom() {
+ break;
+ }
+ let toast_area = Rect::new(
+ area.right().saturating_sub(width).saturating_sub(2),
+ y,
+ width,
+ 3,
+ );
+ crate::tui::clear_area(frame, toast_area, theme);
+ let (symbol, style) = notification_style(notification.kind, theme, basic_terminal);
+ let block = Block::default()
+ .title(Line::from(vec![
+ Span::styled(format!(" {symbol} "), style),
+ Span::styled(
+ notification.title.clone(),
+ style.add_modifier(Modifier::BOLD),
+ ),
+ Span::raw(" "),
+ ]))
+ .borders(Borders::ALL)
+ .border_type(if basic_terminal {
+ BorderType::Plain
+ } else {
+ BorderType::Rounded
+ })
+ .border_style(style)
+ .padding(ratatui::widgets::Padding::horizontal(1));
+ frame.render_widget(
+ Paragraph::new(message)
+ .style(theme.text)
+ .wrap(Wrap { trim: true })
+ .block(block),
+ toast_area,
+ );
+ y = y.saturating_add(3);
+ }
+}
+
+pub fn centered(
+ area: Rect,
+ desired_width: u16,
+ desired_height: u16,
+ minimum_width: u16,
+ maximum_width: u16,
+) -> Rect {
+ let available_width = area.width.saturating_sub(2).max(1);
+ let available_height = area.height.saturating_sub(2).max(1);
+ let width = desired_width
+ .max(minimum_width.min(available_width))
+ .min(maximum_width)
+ .min(available_width);
+ let height = desired_height.min(available_height).max(1);
+ Rect::new(
+ area.x + area.width.saturating_sub(width) / 2,
+ area.y + area.height.saturating_sub(height) / 2,
+ width,
+ height,
+ )
+}
+
+pub fn clear_modal_area(frame: &mut Frame, bounds: Rect, popup: Rect, theme: &Theme) {
+ const HORIZONTAL_HALO: u16 = 3;
+ const VERTICAL_HALO: u16 = 1;
+
+ let x = popup.x.saturating_sub(HORIZONTAL_HALO).max(bounds.x);
+ let y = popup.y.saturating_sub(VERTICAL_HALO).max(bounds.y);
+ let right = popup
+ .right()
+ .saturating_add(HORIZONTAL_HALO)
+ .min(bounds.right());
+ let bottom = popup
+ .bottom()
+ .saturating_add(VERTICAL_HALO)
+ .min(bounds.bottom());
+ crate::tui::clear_area(
+ frame,
+ Rect::new(x, y, right.saturating_sub(x), bottom.saturating_sub(y)),
+ theme,
+ );
+}
+
+fn key_hint(key: &str, action: &str, theme: &Theme) -> Span<'static> {
+ Span::styled(format!("[{key}] {action}"), theme.text_dim)
+}
+
+fn notification_style(
+ kind: NotificationKind,
+ theme: &Theme,
+ basic_terminal: bool,
+) -> (&'static str, Style) {
+ match kind {
+ NotificationKind::Info => ("i", theme.sapphire),
+ NotificationKind::Success => (if basic_terminal { "+" } else { "✓" }, theme.success),
+ NotificationKind::Warning => ("!", theme.rating),
+ NotificationKind::Error => (if basic_terminal { "x" } else { "×" }, theme.error),
+ }
+}
+
+fn middle_truncate(value: &str, maximum_width: usize) -> String {
+ if crate::tui::text::width(value) <= maximum_width {
+ return value.to_string();
+ }
+ let side = maximum_width.saturating_sub(1) / 2;
+ let start = crate::tui::text::truncate_width(value, side);
+ let reversed = value.chars().rev().collect::<String>();
+ let end = crate::tui::text::truncate_width(&reversed, side)
+ .chars()
+ .rev()
+ .collect::<String>();
+ format!("{start}…{end}")
+}
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index b8650d0..a0d4c20 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -185,10 +185,10 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let show_poster = !matches!(tier, DetailsLayoutTier::Tiny)
&& inner_area.height >= 6
&& inner_area.width >= 60;
- let poster_width = if show_poster && state.image_supported {
- ((inner_area.height as f32 * 0.78).ceil() as u16).clamp(8, 18)
- } else if show_poster {
- 16.min(inner_area.width / 4)
+ let poster_width = if show_poster {
+ ((inner_area.height as f32 * 1.33).ceil() as u16)
+ .clamp(10, 22)
+ .min(inner_area.width / 3)
} else {
0
};
@@ -203,8 +203,10 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.split(inner_area);
let poster_height = ((poster_width as f32) / 1.33).ceil() as u16;
+ let poster_height = h_chunks[0].height.min(poster_height);
let poster_area = ratatui::layout::Rect {
- height: h_chunks[0].height.min(poster_height),
+ y: h_chunks[0].y + h_chunks[0].height.saturating_sub(poster_height) / 2,
+ height: poster_height,
..h_chunks[0]
};
let right_area = h_chunks[2];
@@ -914,94 +916,62 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
frame.render_widget(streams_block, streams_area);
}
if state.subtitle_popup || state.is_download_subtitle_popup {
- let popup_width = 50;
- let popup_height = std::cmp::min(15, state.subtitle_list.len() as u16 + 2);
-
- let area = frame.area();
- let popup_area = ratatui::layout::Rect {
- x: area.width.saturating_sub(popup_width) / 2,
- y: area.height.saturating_sub(popup_height) / 2,
- width: popup_width,
- height: popup_height,
- };
-
- crate::tui::clear_area(frame, popup_area, theme);
-
- let items: Vec<ratatui::widgets::ListItem> = state
+ let items = state
.subtitle_list
.iter()
- .map(|(name, _)| ratatui::widgets::ListItem::new(name.clone()))
- .collect();
-
- let title = if state.is_download_subtitle_popup {
- " Select Subtitle to Download "
- } else {
- " Select Subtitle "
- };
-
- let list = ratatui::widgets::List::new(items)
- .block(
- ratatui::widgets::Block::default()
- .title(title)
- .title_style(theme.title)
- .borders(ratatui::widgets::Borders::ALL)
- .border_type(if state.basic_terminal {
- ratatui::widgets::BorderType::Plain
- } else {
- ratatui::widgets::BorderType::Rounded
- })
- .border_style(theme.border),
- )
- .highlight_style(theme.highlight)
- .highlight_symbol(if state.basic_terminal { "> " } else { "▌ " });
-
- frame.render_stateful_widget(list, popup_area, &mut state.subtitle_list_state);
+ .map(|(name, _)| {
+ if name == "None" {
+ "No subtitles".to_string()
+ } else {
+ name.clone()
+ }
+ })
+ .collect::<Vec<_>>();
+ crate::tui::overlay::picker(
+ frame,
+ area,
+ &items,
+ &mut state.subtitle_list_state,
+ crate::tui::overlay::PickerSpec {
+ title: "Subtitles",
+ confirm_label: if state.is_download_subtitle_popup {
+ "Download"
+ } else {
+ "Use"
+ },
+ minimum_width: 32,
+ },
+ theme,
+ state.basic_terminal,
+ );
}
if state.player_picker_popup {
- let popup_width = 24;
- let popup_height = std::cmp::min(15, state.available_players.len() as u16 + 2);
-
- let area = frame.area();
- let popup_area = ratatui::layout::Rect {
- x: area.width.saturating_sub(popup_width) / 2,
- y: area.height.saturating_sub(popup_height) / 2,
- width: popup_width,
- height: popup_height,
- };
-
- crate::tui::clear_area(frame, popup_area, theme);
-
- let items: Vec<ratatui::widgets::ListItem> = state
+ let items = state
.available_players
.iter()
.map(|k| {
- let text = match k {
+ match k {
crate::tui::state::PlayerKind::Mpv => "mpv",
crate::tui::state::PlayerKind::Iina => "IINA",
crate::tui::state::PlayerKind::Vlc => "VLC",
- };
- ratatui::widgets::ListItem::new(text)
+ }
+ .to_string()
})
- .collect();
-
- let list = ratatui::widgets::List::new(items)
- .block(
- ratatui::widgets::Block::default()
- .title(" Open With ")
- .title_style(theme.title)
- .borders(ratatui::widgets::Borders::ALL)
- .border_type(if state.basic_terminal {
- ratatui::widgets::BorderType::Plain
- } else {
- ratatui::widgets::BorderType::Rounded
- })
- .border_style(theme.border),
- )
- .highlight_style(theme.highlight)
- .highlight_symbol(if state.basic_terminal { "> " } else { "▌ " });
-
- frame.render_stateful_widget(list, popup_area, &mut state.player_picker_state);
+ .collect::<Vec<_>>();
+ crate::tui::overlay::picker(
+ frame,
+ area,
+ &items,
+ &mut state.player_picker_state,
+ crate::tui::overlay::PickerSpec {
+ title: "Open with",
+ confirm_label: "Open",
+ minimum_width: 24,
+ },
+ theme,
+ state.basic_terminal,
+ );
}
let (mut primary_footer, secondary_footer) = details_footer(state, theme, area.width);
@@ -1018,146 +988,89 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
frame.render_widget(footer_p, chunks[3]);
if state.show_season_download_confirm {
- let popup_width = 50;
- let popup_height = 7;
- let popup_area = Rect::new(
- (area.width.saturating_sub(popup_width)) / 2,
- (area.height.saturating_sub(popup_height)) / 2,
- popup_width,
- popup_height,
- );
- crate::tui::clear_area(frame, popup_area, theme);
-
let season_idx = state.selected_season;
let eps_count = if season_idx > 0 && season_idx <= state.available_episode_numbers.len() {
state.available_episode_numbers[season_idx - 1].len()
} else {
0
};
-
- let msg = format!(
- "Download all {} episodes in Season {}?",
- eps_count, season_idx
+ crate::tui::overlay::confirmation(
+ frame,
+ area,
+ "Download season",
+ &[
+ Line::from(format!("Season {season_idx}")),
+ Line::from(format!("{eps_count} episodes")),
+ ],
+ state.season_download_confirm_yes_selected,
+ theme,
+ state.basic_terminal,
);
- let yes_text = if state.season_download_confirm_yes_selected {
- " < Yes > "
- } else {
- " Yes "
- };
- let no_text = if !state.season_download_confirm_yes_selected {
- " < No > "
- } else {
- " No "
- };
-
- let confirm_block = Block::default()
- .borders(Borders::ALL)
- .border_style(theme.border_focus)
- .title(" Season Download ")
- .title_alignment(Alignment::Center);
-
- let lines = vec![
- Line::from(""),
- Line::from(msg),
- Line::from(""),
- Line::from(vec![
- Span::styled(
- yes_text,
- if state.season_download_confirm_yes_selected {
- theme.highlight
- } else {
- theme.text_dim
- },
- ),
- Span::raw(" "),
- Span::styled(
- no_text,
- if !state.season_download_confirm_yes_selected {
- theme.highlight
- } else {
- theme.text_dim
- },
- ),
- ]),
- ];
-
- let p = Paragraph::new(lines)
- .block(confirm_block)
- .alignment(Alignment::Center)
- .style(theme.text);
-
- frame.render_widget(p, popup_area);
} else if state.show_episode_download_confirm {
- let popup_width = 50;
- let popup_height = 7;
- let popup_area = Rect::new(
- (area.width.saturating_sub(popup_width)) / 2,
- (area.height.saturating_sub(popup_height)) / 2,
- popup_width,
- popup_height,
- );
- crate::tui::clear_area(frame, popup_area, theme);
-
let season_idx = state.selected_season;
let ep_idx = state.selected_episode;
-
- let msg = if type_val == 2 {
- format!("Download Episode {} of Season {}?", ep_idx, season_idx)
- } else {
- "Download this Movie?".to_string()
- };
-
- let yes_text = if state.episode_download_confirm_yes_selected {
- " < Yes > "
- } else {
- " Yes "
- };
- let no_text = if !state.episode_download_confirm_yes_selected {
- " < No > "
+ let mut summary = if type_val == 2 {
+ vec![Line::from(format!(
+ "Season {season_idx} · Episode {ep_idx}"
+ ))]
} else {
- " No "
+ vec![Line::from("Download this movie")]
};
-
- let confirm_block = Block::default()
- .borders(Borders::ALL)
- .border_style(theme.border_focus)
- .title(" Download ")
- .title_alignment(Alignment::Center);
-
- let lines = vec![
- Line::from(""),
- Line::from(msg),
- Line::from(""),
- Line::from(vec![
- Span::styled(
- yes_text,
- if state.episode_download_confirm_yes_selected {
- theme.highlight
- } else {
- theme.text_dim
- },
- ),
- Span::raw(" "),
- Span::styled(
- no_text,
- if !state.episode_download_confirm_yes_selected {
- theme.highlight
- } else {
- theme.text_dim
- },
- ),
- ]),
- ];
-
- let p = Paragraph::new(lines)
- .block(confirm_block)
- .alignment(Alignment::Center)
- .style(theme.text);
-
- frame.render_widget(p, popup_area);
+ if let Some(stream) = selected_stream_summary(state) {
+ summary.push(Line::from(stream));
+ }
+ crate::tui::overlay::confirmation(
+ frame,
+ area,
+ if type_val == 2 {
+ "Download episode"
+ } else {
+ "Download movie"
+ },
+ &summary,
+ state.episode_download_confirm_yes_selected,
+ theme,
+ state.basic_terminal,
+ );
}
}
+fn selected_stream_summary(state: &AppState) -> Option<String> {
+ let resource = state
+ .selected_resources
+ .as_ref()?
+ .get("list")?
+ .as_array()?
+ .get(state.resource_list_state.selected().unwrap_or(0))?;
+ let resolution = resource
+ .get("resolution")
+ .and_then(|value| value.as_i64())
+ .filter(|value| *value > 0)
+ .map(|value| format!("{value}p"));
+ let codec = resource
+ .get("codecName")
+ .and_then(|value| value.as_str())
+ .filter(|value| !value.is_empty())
+ .map(str::to_uppercase);
+ let size = resource
+ .get("size")
+ .and_then(|value| value.as_str())
+ .and_then(|value| value.parse::<f64>().ok())
+ .map(|bytes| {
+ let megabytes = bytes / 1024.0 / 1024.0;
+ if megabytes > 1024.0 {
+ format!("{:.1} GB", megabytes / 1024.0)
+ } else {
+ format!("{megabytes:.0} MB")
+ }
+ });
+ let fields = [size, resolution, codec]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>();
+ (!fields.is_empty()).then(|| fields.join(" · "))
+}
+
fn truncate_with_ellipsis(value: &str, capacity: usize) -> String {
if capacity == 0 {
return String::new();
diff --git a/src/tui/screens/help.rs b/src/tui/screens/help.rs
index 4314527..5e53161 100644
--- a/src/tui/screens/help.rs
+++ b/src/tui/screens/help.rs
@@ -1,7 +1,7 @@
use crate::tui::{state::AppState, theme::Theme};
use ratatui::{
Frame,
- layout::{Alignment, Constraint, Direction, Layout, Rect},
+ layout::{Alignment, Rect},
text::{Line, Span},
widgets::{Block, BorderType, Borders, Paragraph},
};
@@ -165,28 +165,16 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
]);
}
- let height = help_text.len() as u16 + 2;
- let margin_y = area.height.saturating_sub(height) / 2;
+ let content_width = help_text.iter().map(Line::width).max().unwrap_or(42);
+ let popup_chunk = crate::tui::overlay::centered(
+ area,
+ content_width.saturating_add(4) as u16,
+ help_text.len() as u16 + 2,
+ 46,
+ 64,
+ );
- let popup_layout = Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(margin_y),
- Constraint::Length(height),
- Constraint::Min(0),
- ])
- .split(area);
-
- let popup_chunk = Layout::default()
- .direction(Direction::Horizontal)
- .constraints([
- Constraint::Percentage(25),
- Constraint::Min(45),
- Constraint::Percentage(25),
- ])
- .split(popup_layout[1])[1];
-
- crate::tui::clear_area(frame, popup_chunk, theme);
+ crate::tui::overlay::clear_modal_area(frame, area, popup_chunk, theme);
let block = Block::default()
.title(" Keybindings Help ")
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index df16443..f51e284 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -703,15 +703,23 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
if state.tv_config_popup {
let content_height = state.tv_wizard_options.len() as u16;
- let max_height = area.height.saturating_sub(17).max(6);
- let popup_height = (content_height + 4).clamp(6, max_height);
-
- let popup_area = ratatui::layout::Rect {
- x: area.width.saturating_sub(44) / 2,
- y: 13.min(area.height.saturating_sub(popup_height)),
- width: 44,
- height: popup_height,
- };
+ let content_width = state
+ .tv_wizard_options
+ .iter()
+ .map(|option| crate::tui::text::width(option))
+ .max()
+ .unwrap_or(32)
+ .max(crate::tui::text::width(
+ "[Space] Toggle [Enter] Confirm [Esc] Back",
+ ));
+ let popup_area = crate::tui::overlay::centered(
+ area,
+ content_width.saturating_add(6) as u16,
+ content_height.min(8) + 3,
+ 36,
+ 64,
+ );
+ crate::tui::overlay::clear_modal_area(frame, area, popup_area, theme);
let popup_block = ratatui::widgets::Block::default()
.title(if state.tv_wizard_step == 0 {
" TV Setup: Select Grouping "
@@ -803,49 +811,31 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
if state.player_picker_popup {
- let popup_width = 24;
- let popup_height = std::cmp::min(15, state.available_players.len() as u16 + 2);
-
- let area = frame.area();
- let popup_area = ratatui::layout::Rect {
- x: area.width.saturating_sub(popup_width) / 2,
- y: area.height.saturating_sub(popup_height) / 2,
- width: popup_width,
- height: popup_height,
- };
-
- crate::tui::clear_area(frame, popup_area, theme);
-
- let items: Vec<ratatui::widgets::ListItem> = state
+ let items = state
.available_players
.iter()
.map(|k| {
- let text = match k {
+ match k {
crate::tui::state::PlayerKind::Mpv => "mpv",
crate::tui::state::PlayerKind::Iina => "IINA",
crate::tui::state::PlayerKind::Vlc => "VLC",
- };
- ratatui::widgets::ListItem::new(text)
+ }
+ .to_string()
})
- .collect();
-
- let list = ratatui::widgets::List::new(items)
- .block(
- ratatui::widgets::Block::default()
- .title(" Open With ")
- .title_style(theme.title)
- .borders(ratatui::widgets::Borders::ALL)
- .border_type(if state.basic_terminal {
- ratatui::widgets::BorderType::Plain
- } else {
- ratatui::widgets::BorderType::Rounded
- })
- .border_style(theme.border),
- )
- .highlight_style(theme.highlight)
- .highlight_symbol(if state.basic_terminal { "> " } else { "▌ " });
-
- frame.render_stateful_widget(list, popup_area, &mut state.player_picker_state);
+ .collect::<Vec<_>>();
+ crate::tui::overlay::picker(
+ frame,
+ area,
+ &items,
+ &mut state.player_picker_state,
+ crate::tui::overlay::PickerSpec {
+ title: "Open with",
+ confirm_label: "Open",
+ minimum_width: 24,
+ },
+ theme,
+ state.basic_terminal,
+ );
}
}
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 33a5a73..dca2143 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -120,8 +120,7 @@ pub struct AppState {
pub is_loading: bool,
pub status_message: String,
pub status_timer: usize,
- pub toast_message: Option<String>,
- pub toast_timer: usize,
+ pub notifications: std::collections::VecDeque<crate::tui::overlay::Notification>,
pub update_available: Option<String>,
pub updater_progress: Option<f64>,
pub updater_status: Option<String>,
@@ -184,9 +183,9 @@ impl Default for AppState {
stream_pool: std::collections::HashMap::new(),
fetch_cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
show_season_download_confirm: false,
- season_download_confirm_yes_selected: true,
+ season_download_confirm_yes_selected: false,
show_episode_download_confirm: false,
- episode_download_confirm_yes_selected: true,
+ episode_download_confirm_yes_selected: false,
is_waiting_for_download_stream: false,
is_downloading: false,
is_fetching_streams: false,
@@ -227,8 +226,7 @@ impl Default for AppState {
is_loading: false,
status_message: String::new(),
status_timer: 0,
- toast_message: None,
- toast_timer: 0,
+ notifications: std::collections::VecDeque::new(),
update_available: None,
updater_progress: None,
updater_status: None,
@@ -272,3 +270,30 @@ impl Default for AppState {
}
}
}
+
+impl AppState {
+ pub fn notify(
+ &mut self,
+ kind: crate::tui::overlay::NotificationKind,
+ title: impl Into<String>,
+ message: impl Into<String>,
+ ) {
+ if self.notifications.len() >= 3 {
+ let removable = self
+ .notifications
+ .iter()
+ .position(|notification| {
+ notification.kind != crate::tui::overlay::NotificationKind::Error
+ })
+ .unwrap_or(0);
+ self.notifications.remove(removable);
+ }
+ self.notifications
+ .push_back(crate::tui::overlay::Notification::new(kind, title, message));
+ }
+
+ pub fn expire_notifications(&mut self) {
+ self.notifications
+ .retain(|notification| !notification.expired());
+ }
+}