Skip to content

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

feat(download): redesign download bar and smooth monotonic dash progress

Samir Hossains32ccde39e4ac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 631b66d..b00c785 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@
- Replaced immediate mouse cycling on the landing search bar provider badge (`[MovieBox · ^P]`) with a styled popup menu anchored directly beneath the provider badge.
- Added dedicated keyboard navigation (`↑`/`↓`/`k`/`j`, `Home`/`End`, `Enter`/`Space`, `Esc`) for the provider menu while preserving direct `Ctrl+P` sequential provider cycling across all screens.
- Implemented shared geometry (`search_bar_provider_pill_rect` and `provider_popup_bounds`) between renderers and mouse hitboxes, ensuring exact alignment and zero geometry divergence.
+- **Redesigned High-Contrast Download Bar & Responsive Layout**:
+ - Replaced the solid rectangular download gauge with a sleek proportional track (`[━━━━━────]` on modern terminals and `[=====>----]` on basic terminals) with filled accent contrast and dimmed surface rail.
+ - Added prominent media title indicators on the top border (`⬇ Downloading: <Title>` or `⬇ S<N>E<N> (<current>/<total>): <Title>`) with bold styling and automatic terminal width truncation.
+ - Replaced ambiguous whole-area click cancellation with an isolated `[x] Cancel` button hitbox on the top-right border, preventing accidental download interruptions while keeping the bar mouse-safe.
+ - Formatted transfer statistics into clean badges (`<Size> | <Speed> | ETA <Time>`) with zero unclosed parenthesis artifacts and zero floating dots.
- **Native Android ARM64 Release Target & Pipeline**:
- Added native `aarch64-linux-android` build target to the release workflow (`.github/workflows/release.yml`) using Android NDK r26d and Clang (API 24+).
- Configured automated packaging of `MovieBox_Android_arm64.tar.gz` with native Bionic dynamic linking (`libc.so`), valid ELF `PT_PHDR` program header table, and `/system/bin/linker64` dynamic loader.
@@ -22,6 +27,11 @@
- Added documentation build integrity validation step in CI hygiene pipeline (`.github/workflows/ci.yml`).
### Fixed
+- **MovieBox DASH Progress Normalization, Throttling & Background Continuity**:
+ - Normalized multi-stream MPEG-DASH download percentages across video (0–90%), audio (90–98%), and merger (99–100%) stages, eliminating progress resets back to 0% when the video stream finishes and the audio stream begins.
+ - Enforced monotonic progress tracking and throttled progress event emissions to 250ms intervals, eliminating terminal text jitter and channel saturation.
+ - Preserved active downloads and queue processing across content provider switching (`Ctrl+P`) and mode toggling (`Ctrl+T`, `Ctrl+A`), eliminating premature download pauses and false cancellation warnings when navigating the TUI.
+ - Added explicit cancellation feedback notifications when dismissing the subtitle selection popup via `Esc` or outside mouse click, preventing silent stream launch cancellations.
- **Empty Search Clear Guarding on Landing Screen**:
- Guarded search-cleared status notifications in `Action::GoBack`, `c`/`C`, and `Ctrl+U` to only fire when an active search query or loaded results actually existed, eliminating spurious "Search cleared." status messages when navigating on an already-empty landing page.
- Allowed pressing Enter on an empty search input in editing mode to cleanly switch back to normal mode without triggering unneeded state resets.
diff --git a/docs/controls.md b/docs/controls.md
index 5691669..59bc946 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -19,6 +19,7 @@ MovieBox-TUI is designed for fast keyboard navigation with complete mouse suppor
| **`Ctrl+U`** | Clear entire input line (Search, TV URL, Addon URL) |
| **`Ctrl+W`** | Delete backward word in text inputs |
| **`c`** | Clear active search query and return to landing screen (Normal mode) |
+| **`x` / `X`** | Cancel active download and preserve partial `.part` data |
| **`Ctrl+S`** | Switch to standard **Streaming Mode** |
| **`Ctrl+T`** | Toggle / switch to **TV Mode** |
| **`Ctrl+A`** | Toggle / switch to **Addon Mode** |
@@ -91,6 +92,7 @@ All popup dialogs (Theme picker, Browse categories, Provider menu, Settings Medi
| **Click search bar** | Enter search input mode |
| **Click search result row** | Select item and load preview; click again to open full details |
| **Click landing deck tab header** | Switch between Continue Watching and Favorites tabs |
+| **`Click [x] Cancel on download bar`** | Cancel active download |
| **Click Continue Watching row (landing)** | Select an in-progress title; click again to resume playback with auto-play |
| **Click Favorites row (landing)** | Select a starred title; click again to open details |
| **Click "+N more • /history" or "+N more • /favorites"** | Open the full watch history or favorites list |
diff --git a/docs/downloads.md b/docs/downloads.md
index 044d5b9..6b8657f 100644
--- a/docs/downloads.md
+++ b/docs/downloads.md
@@ -51,6 +51,14 @@ and length is capped.
Selected subtitle sidecars are saved next to the video using ISO 639-1 language codes (e.g. `.en.srt`, `.hi.srt`) and supported subtitle extensions (`.srt`, `.vtt`, `.ass`, `.ssa`, `.sub`).
+## Download Bar & Progress Architecture
+
+- **High-Contrast Responsive Bar**: Renders a proportional progress track (`[━━━━━────]` on modern terminals and `[=====>----]` on basic terminals) with prominent media title display (`⬇ Downloading: <Title>`), percentage badge, and separated transfer metrics (`<Size> | <Speed> | ETA <Time>`).
+- **Monotonic DASH Normalization**: Multi-stream MPEG-DASH downloads via `yt-dlp` automatically normalize segmented tracks (video 0–90%, audio 90–98%, and track merger 99–100%) so that progress strictly increases and never resets backwards to 0% mid-download.
+- **Throttled Updates**: Progress events are throttled to 250ms intervals, eliminating terminal flicker and event-channel flooding from high-frequency chunk streams.
+- **Background Download Continuity**: Downloads continue running uninterrupted in the background when switching content providers (`Ctrl+P`) or toggling modes (`Ctrl+T`, `Ctrl+A`), keeping all active transfer workers and queues alive.
+- **Isolated Cancellation Hitbox**: Cancellation is bound strictly to the `x` / `X` keyboard shortcut and the `[x] Cancel` button in the top-right corner of the download bar. Clicking anywhere else on the bar safely consumes the mouse event without interrupting active downloads.
+
## Outcomes
`DownloadCompleted` / `DownloadPaused` / `DownloadFailed` drive the UI status and
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 5978b37..08bf670 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -95,6 +95,7 @@ impl App {
.or_else(|| self.state.season_subtitle_preference.clone().flatten());
self.state.is_waiting_for_download_stream = false;
+ self.state.download_title = Some(base_name.clone());
self.state.download_status = Some("Preparing download...".into());
self.state.download_progress = Some(0.0);
self.state
@@ -281,6 +282,11 @@ impl App {
if let Some(stdout) = child.stdout.take() {
use tokio::io::AsyncBufReadExt;
let mut reader = tokio::io::BufReader::new(stdout).lines();
+ let mut stream_index: usize = 0;
+ let mut max_progress: f64 = 0.0;
+ let mut last_send =
+ std::time::Instant::now() - std::time::Duration::from_secs(1);
+
loop {
if cancel.load(std::sync::atomic::Ordering::Relaxed) {
let _ = child.kill().await;
@@ -306,17 +312,31 @@ impl App {
line_res = reader.next_line() => {
match line_res {
Ok(Some(line)) => {
- if let Some((pct, status)) = parse_ytdlp_progress(&line) {
- sender
- .send(Action::UpdateDownload(Some(pct), Some(status)))
- .ok();
- } else if line.contains("[Merger]") {
+ if line.contains("[download] Destination:") {
+ stream_index = stream_index.saturating_add(1);
+ } else if let Some((raw_pct, status)) = parse_ytdlp_progress(&line) {
+ let current_stream = stream_index.max(1);
+ let (normalized_pct, display_status) = if current_stream <= 1 {
+ (raw_pct * 0.90, status)
+ } else {
+ (90.0 + (raw_pct * 0.08), format!("Audio | {status}"))
+ };
+ max_progress = max_progress.max(normalized_pct);
+ if last_send.elapsed() >= std::time::Duration::from_millis(250) || raw_pct >= 99.9 {
+ sender
+ .send(Action::UpdateDownload(Some(max_progress), Some(display_status)))
+ .ok();
+ last_send = std::time::Instant::now();
+ }
+ } else if line.contains("[Merger]") || line.contains("[ffmpeg]") {
+ max_progress = max_progress.max(99.0);
sender
.send(Action::UpdateDownload(
- Some(99.0),
- Some("Merging audio and video...".to_string()),
+ Some(max_progress),
+ Some("Merging audio & video...".to_string()),
))
.ok();
+ last_send = std::time::Instant::now();
}
}
Ok(None) => break,
@@ -717,6 +737,7 @@ impl App {
Action::DownloadFailed(error) => {
self.state.download_progress = None;
self.state.download_status = None;
+ self.state.download_title = None;
if self.state.download_queue_total > 0 {
let total = self.state.download_queue_total;
let remaining = self.state.download_queue.len();
@@ -739,6 +760,7 @@ impl App {
Action::DownloadPaused(path) => {
self.state.download_progress = None;
self.state.download_status = None;
+ self.state.download_title = None;
if self.state.download_queue_total > 0 {
let total = self.state.download_queue_total;
let remaining = self.state.download_queue.len();
@@ -761,6 +783,7 @@ impl App {
Action::ClearDownload => {
self.state.download_progress = None;
self.state.download_status = None;
+ self.state.download_title = None;
if !self.state.download_queue.is_empty() {
self.action_sender.send(Action::ProcessDownloadQueue).ok();
} else if self.state.download_queue_total > 0 {
@@ -908,21 +931,84 @@ pub(crate) fn yt_dlp_missing_guidance() -> String {
}
pub(crate) fn parse_ytdlp_progress(line: &str) -> Option<(f64, String)> {
- if !line.contains("[download]") {
+ if !line.contains("[download]") || line.contains("Destination:") {
return None;
}
let trimmed = line.split("[download]").nth(1)?.trim();
- let mut percentage = None;
- for part in trimmed.split_whitespace() {
- if let Some(num_str) = part.strip_suffix('%') {
- if let Ok(pct) = num_str.parse::<f64>() {
- percentage = Some(pct);
- break;
+ let words: Vec<&str> = trimmed.split_whitespace().collect();
+ if words.is_empty() {
+ return None;
+ }
+
+ let pct_str = words.iter().find(|w| w.ends_with('%'))?;
+ let pct: f64 = pct_str.trim_end_matches('%').parse().ok()?;
+
+ if trimmed.contains(" in ") {
+ let size = words
+ .iter()
+ .position(|&w| w == "of")
+ .and_then(|idx| words.get(idx + 1))
+ .copied()
+ .unwrap_or("");
+ let duration = words
+ .iter()
+ .position(|&w| w == "in")
+ .and_then(|idx| words.get(idx + 1))
+ .copied()
+ .unwrap_or("");
+ if !size.is_empty() && !duration.is_empty() {
+ return Some((pct, format!("{size} in {duration}")));
+ }
+ }
+
+ let mut size_parts = Vec::new();
+ let mut speed = "";
+ let mut eta = "";
+
+ if let Some(of_idx) = words.iter().position(|&w| w == "of") {
+ let at_idx = words.iter().position(|&w| w == "at").unwrap_or(words.len());
+ for &w in &words[of_idx + 1..at_idx] {
+ let clean = w.trim_matches('~').trim();
+ if !clean.is_empty() {
+ size_parts.push(clean);
+ }
+ }
+ }
+
+ if let Some(at_idx) = words.iter().position(|&w| w == "at") {
+ if let Some(&s) = words.get(at_idx + 1) {
+ speed = s;
+ }
+ }
+
+ if let Some(eta_idx) = words.iter().position(|&w| w == "ETA") {
+ if let Some(&e) = words.get(eta_idx + 1) {
+ let clean_eta = e.trim_end_matches(['(', ')', ',']);
+ if !clean_eta.eq_ignore_ascii_case("unknown") {
+ eta = clean_eta;
}
}
}
- let pct = percentage?;
- Some((pct, trimmed.to_string()))
+
+ let size = size_parts.join(" ");
+ let mut parts = Vec::new();
+ if !size.is_empty() {
+ parts.push(size);
+ }
+ if !speed.is_empty() {
+ parts.push(speed.to_string());
+ }
+ if !eta.is_empty() {
+ parts.push(format!("ETA {eta}"));
+ }
+
+ let status = if parts.is_empty() {
+ trimmed.to_string()
+ } else {
+ parts.join(" | ")
+ };
+
+ Some((pct, status))
}
#[cfg(test)]
@@ -1000,20 +1086,24 @@ mod tests {
assert!(res1.is_some());
let (pct1, status1) = res1.unwrap();
assert!((pct1 - 0.0).abs() < f64::EPSILON);
- assert!(status1.contains("5.19MiB"));
+ assert_eq!(status1, "5.19MiB | 0.00B/s");
+ assert!(!status1.contains('~'));
+ assert!(!status1.contains("Unknown"));
+ assert!(!status1.contains("(frag"));
let line2 = "[download] 45.2% of ~ 1.45GiB at 12.3MiB/s ETA 00:45 (frag 500/1676)";
let res2 = super::parse_ytdlp_progress(line2);
assert!(res2.is_some());
let (pct2, status2) = res2.unwrap();
assert!((pct2 - 45.2).abs() < f64::EPSILON);
- assert!(status2.contains("12.3MiB/s"));
+ assert_eq!(status2, "1.45GiB | 12.3MiB/s | ETA 00:45");
let line3 = "[download] 100% of 1.45GiB in 02:15";
let res3 = super::parse_ytdlp_progress(line3);
assert!(res3.is_some());
- let (pct3, _) = res3.unwrap();
+ let (pct3, status3) = res3.unwrap();
assert!((pct3 - 100.0).abs() < f64::EPSILON);
+ assert_eq!(status3, "1.45GiB in 02:15");
let line_non = "[generic] Extracting URL: https://example.com/index.mpd";
assert!(super::parse_ytdlp_progress(line_non).is_none());
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 4a043d1..9246e08 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -50,7 +50,15 @@ impl App {
.split(area);
let dl_area = chunks[1];
if dl_area.contains(ratatui::layout::Position::new(col, row)) {
- self.action_sender.send(Action::CancelDownload).ok();
+ let cancel_rect = Rect {
+ x: dl_area.right().saturating_sub(14),
+ y: dl_area.y,
+ width: 14.min(dl_area.width),
+ height: 1,
+ };
+ if cancel_rect.contains(ratatui::layout::Position::new(col, row)) {
+ self.action_sender.send(Action::CancelDownload).ok();
+ }
return true;
}
}
@@ -300,8 +308,24 @@ impl App {
}
Some(None) => {}
None => {
+ let is_dl = self.state.is_download_subtitle_popup;
+ self.state.is_resolving_playback = false;
self.state.subtitle_popup = false;
self.state.is_download_subtitle_popup = false;
+ self.state.pending_play_link = None;
+ self.state.pending_playback_source = None;
+ self.state.subtitle_list.clear();
+ self.state.subtitle_list_state.select(None);
+ if is_dl {
+ self.state
+ .set_status_default("Download subtitle selection cancelled.");
+ } else {
+ self.state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Playback Cancelled",
+ "Stream launch cancelled.",
+ );
+ }
}
}
return true;
@@ -1458,4 +1482,38 @@ mod tests {
assert!(!app.state.show_provider_popup);
assert_eq!(app.state.active_provider, ProviderKind::FourKHdHub);
}
+
+ #[tokio::test]
+ async fn test_download_cancel_mouse_hitbox() {
+ let mut app = App::new();
+ let area = Rect::new(0, 0, 80, 24);
+ app.state.download_progress = Some(50.0);
+ app.state
+ .cancel_download
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+ let handled = app.handle_overlay_mouse(20, 22, area);
+ assert!(handled);
+ assert!(app.action_receiver.try_recv().is_err());
+
+ let handled_cancel = app.handle_overlay_mouse(72, 21, area);
+ assert!(handled_cancel);
+ assert!(matches!(
+ app.action_receiver.try_recv().ok(),
+ Some(Action::CancelDownload)
+ ));
+ }
+
+ #[tokio::test]
+ async fn test_subtitle_popup_outside_click_emits_cancellation() {
+ let mut app = App::new();
+ let area = Rect::new(0, 0, 80, 24);
+ app.state.subtitle_popup = true;
+ app.state.subtitle_list = vec![("English".to_string(), "https://sub.url".to_string())];
+
+ let handled = app.handle_overlay_mouse(0, 0, area);
+ assert!(handled);
+ assert!(!app.state.subtitle_popup);
+ let notif = app.state.notifications.back().expect("notification posted");
+ assert_eq!(notif.title, "Playback Cancelled");
+ }
}
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index eadac02..a679f38 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -43,13 +43,6 @@ impl App {
self.state.stream_pool.clear();
self.state.has_streams_settled = false;
self.state.has_search_settled = false;
- self.state
- .cancel_download
- .store(true, std::sync::atomic::Ordering::SeqCst);
- self.state.download_progress = None;
- self.state.download_status = None;
- self.state.download_queue.clear();
- self.state.download_queue_total = 0;
self.state.is_waiting_for_download_stream = false;
self.state.clear_poster_cache();
self.state.image_cache.clear();
@@ -345,6 +338,7 @@ impl App {
return None;
}
if self.state.subtitle_popup || self.state.is_download_subtitle_popup {
+ let is_dl = self.state.is_download_subtitle_popup;
self.state.is_resolving_playback = false;
self.state.subtitle_popup = false;
self.state.is_download_subtitle_popup = false;
@@ -352,6 +346,16 @@ impl App {
self.state.pending_playback_source = None;
self.state.subtitle_list.clear();
self.state.subtitle_list_state.select(None);
+ if is_dl {
+ self.state
+ .set_status_default("Download subtitle selection cancelled.");
+ } else {
+ self.state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Playback Cancelled",
+ "Stream launch cancelled.",
+ );
+ }
return None;
}
if self.state.show_help {
@@ -916,3 +920,53 @@ impl App {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::providers::models::ProviderKind;
+ use crate::tui::action::Action;
+ use crate::tui::app::App;
+ use crate::tui::overlay::NotificationKind;
+
+ #[tokio::test]
+ async fn test_switch_provider_preserves_active_download() {
+ let mut app = App::new();
+ app.state.download_progress = Some(45.0);
+ app.state.download_status = Some("45MB".to_string());
+ app.state.download_title = Some("Test Movie".to_string());
+ app.state
+ .cancel_download
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+
+ app.switch_provider(ProviderKind::FourKHdHub);
+
+ assert_eq!(app.state.active_provider, ProviderKind::FourKHdHub);
+ assert_eq!(app.state.download_progress, Some(45.0));
+ assert_eq!(app.state.download_status.as_deref(), Some("45MB"));
+ assert_eq!(app.state.download_title.as_deref(), Some("Test Movie"));
+ assert!(
+ !app.state
+ .cancel_download
+ .load(std::sync::atomic::Ordering::SeqCst)
+ );
+ }
+
+ #[tokio::test]
+ async fn test_subtitle_popup_cancellation_feedback() {
+ let mut app = App::new();
+ app.state.subtitle_popup = true;
+ app.state.pending_play_link = Some("https://example.com/video.mp4".to_string());
+
+ app.handle_action(Action::GoBack).await;
+
+ assert!(!app.state.subtitle_popup);
+ assert!(app.state.pending_play_link.is_none());
+ let notif = app
+ .state
+ .notifications
+ .back()
+ .expect("notification emitted");
+ assert_eq!(notif.kind, NotificationKind::Info);
+ assert_eq!(notif.title, "Playback Cancelled");
+ }
+}
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index 55e2b9f..7b71447 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -629,70 +629,190 @@ impl App {
}
fn draw_download_gauge(&self, frame: &mut Frame, download_area: Option<Rect>) {
- if let Some(prog) = self.state.download_progress {
- if let Some(dl_area) = download_area {
- use ratatui::widgets::{Block, Borders, Gauge};
+ let Some(prog) = self.state.download_progress else {
+ return;
+ };
+ let Some(dl_area) = download_area else {
+ return;
+ };
+ if dl_area.width < 16 || dl_area.height < 3 {
+ return;
+ }
- let status = self
- .state
- .download_status
- .as_deref()
- .unwrap_or("Downloading...");
-
- let budget = (dl_area.width as usize).saturating_sub(10);
- let is_compact_gauge = dl_area.width < 60;
- let status_sub = if is_compact_gauge { 16 } else { 30 };
- let status_text = crate::tui::text::truncate_width(
- status,
- budget.saturating_sub(status_sub).max(8),
- );
- let title_text = if self.state.download_queue_total > 0 {
- let total = self.state.download_queue_total;
- let remaining = self.state.download_queue.len();
- let current = total - remaining;
- if is_compact_gauge {
- format!(
- " S{:02}E{:02} ({}/{}) | {} [X] ",
- self.state.selected_season,
- self.state.selected_episode,
- current,
- total,
- status_text
- )
+ use ratatui::layout::Alignment;
+ use ratatui::style::Modifier;
+ use ratatui::text::{Line, Span};
+ use ratatui::widgets::{Block, Borders, Paragraph};
+
+ let is_compact = dl_area.width < 60;
+ let basic = self.state.basic_terminal;
+
+ let raw_title = self
+ .state
+ .download_title
+ .as_deref()
+ .or_else(|| {
+ self.state
+ .selected_details
+ .as_ref()
+ .map(|d| d.title.as_str())
+ })
+ .unwrap_or("Media");
+
+ let cancel_label = if is_compact { "[x]" } else { "[x] Cancel" };
+ let cancel_budget = (crate::tui::text::width(cancel_label) as u16).saturating_add(4);
+
+ let mut left_title_spans = Vec::new();
+ if basic {
+ left_title_spans.push(Span::styled(
+ " [DL] ",
+ self.theme.teal.add_modifier(Modifier::BOLD),
+ ));
+ } else {
+ left_title_spans.push(Span::styled(
+ " ⬇ Downloading: ",
+ self.theme.teal.add_modifier(Modifier::BOLD),
+ ));
+ }
+
+ if self.state.download_queue_total > 0 {
+ let total = self.state.download_queue_total;
+ let remaining = self.state.download_queue.len();
+ let current = total.saturating_sub(remaining);
+ let queue_str = format!(
+ "S{:02}E{:02} ({}/{}): ",
+ self.state.selected_season, self.state.selected_episode, current, total
+ );
+ left_title_spans.push(Span::styled(queue_str, self.theme.sapphire));
+ }
+
+ let prefix_width = left_title_spans.iter().map(Span::width).sum::<usize>() as u16;
+ let title_max_width = dl_area
+ .width
+ .saturating_sub(prefix_width.saturating_add(cancel_budget).saturating_add(4))
+ as usize;
+ let truncated_title = crate::tui::text::truncate_width(raw_title, title_max_width.max(6));
+ left_title_spans.push(Span::styled(
+ truncated_title,
+ self.theme.title.add_modifier(Modifier::BOLD),
+ ));
+ left_title_spans.push(Span::raw(" "));
+
+ let left_title = Line::from(left_title_spans);
+ let right_title = Line::from(vec![Span::styled(
+ format!(" {cancel_label} "),
+ self.theme.error.add_modifier(Modifier::BOLD),
+ )])
+ .alignment(Alignment::Right);
+
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .title(left_title)
+ .title(right_title)
+ .border_style(self.theme.lavender)
+ .border_type(crate::tui::overlay::border_type(basic));
+
+ let inner_area = block.inner(dl_area);
+ crate::tui::clear_area(frame, dl_area, &self.theme);
+ frame.render_widget(block, dl_area);
+
+ if inner_area.height == 0 || inner_area.width < 10 {
+ return;
+ }
+
+ let status_str = self
+ .state
+ .download_status
+ .as_deref()
+ .unwrap_or("Downloading...");
+
+ let pct_val = prog.clamp(0.0, 100.0);
+ let pct_badge = format!(" {:>5.1}% ", pct_val);
+ let pct_width = 8usize;
+
+ let available_for_rest = (inner_area.width as usize).saturating_sub(pct_width + 1);
+
+ let bar_width = if available_for_rest < 20 {
+ 10usize.min(available_for_rest)
+ } else {
+ (available_for_rest / 2).clamp(12, 38)
+ };
+
+ let track_cells = bar_width.saturating_sub(2);
+ let ratio = (pct_val / 100.0).clamp(0.0, 1.0);
+ let filled_cells = ((track_cells as f64) * ratio).round() as usize;
+ let unfilled_cells = track_cells.saturating_sub(filled_cells);
+
+ let mut row_spans = Vec::new();
+ row_spans.push(Span::styled(
+ pct_badge,
+ self.theme.sapphire.add_modifier(Modifier::BOLD),
+ ));
+
+ row_spans.push(Span::styled("[", self.theme.surface1));
+ if basic {
+ if filled_cells > 0 && unfilled_cells > 0 {
+ row_spans.push(Span::styled(
+ "=".repeat(filled_cells.saturating_sub(1)),
+ self.theme.accent.add_modifier(Modifier::BOLD),
+ ));
+ row_spans.push(Span::styled(
+ ">",
+ self.theme.accent.add_modifier(Modifier::BOLD),
+ ));
+ } else {
+ row_spans.push(Span::styled(
+ "=".repeat(filled_cells),
+ self.theme.accent.add_modifier(Modifier::BOLD),
+ ));
+ }
+ row_spans.push(Span::styled(
+ "-".repeat(unfilled_cells),
+ self.theme.surface1,
+ ));
+ } else {
+ row_spans.push(Span::styled(
+ "━".repeat(filled_cells),
+ self.theme.teal.add_modifier(Modifier::BOLD),
+ ));
+ row_spans.push(Span::styled(
+ "─".repeat(unfilled_cells),
+ self.theme.surface1,
+ ));
+ }
+ row_spans.push(Span::styled("] ", self.theme.surface1));
+
+ let status_budget = available_for_rest.saturating_sub(bar_width + 2);
+ if status_budget >= 6 {
+ let truncated_status = crate::tui::text::truncate_width(status_str, status_budget);
+ if truncated_status.contains(" | ") {
+ let parts: Vec<&str> = truncated_status.split(" | ").collect();
+ for (idx, part) in parts.iter().enumerate() {
+ if idx > 0 {
+ row_spans.push(Span::styled(" | ", self.theme.surface1));
+ }
+ if part.starts_with("ETA") {
+ row_spans.push(Span::styled(part.to_string(), self.theme.rating));
+ } else if part.contains("/s") {
+ row_spans.push(Span::styled(
+ part.to_string(),
+ self.theme.teal.add_modifier(Modifier::BOLD),
+ ));
+ } else if part.starts_with("Audio") {
+ row_spans.push(Span::styled(
+ part.to_string(),
+ self.theme.lavender.add_modifier(Modifier::BOLD),
+ ));
} else {
- format!(
- " Download: S{:02}E{:02} ({}/{}) | {} [X] Cancel ",
- self.state.selected_season,
- self.state.selected_episode,
- current,
- total,
- status_text
- )
+ row_spans.push(Span::styled(part.to_string(), self.theme.subtext1));
}
- } else if is_compact_gauge {
- format!(" {} [X] ", status_text)
- } else {
- format!(" Download: {} [X] Cancel ", status_text)
- };
-
- let gauge = Gauge::default()
- .block(
- Block::default()
- .borders(Borders::ALL)
- .title(title_text)
- .border_style(self.theme.lavender)
- .title_style(self.theme.title)
- .border_type(crate::tui::overlay::border_type(
- self.state.basic_terminal,
- )),
- )
- .gauge_style(self.theme.accent)
- .ratio((prog / 100.0).clamp(0.0, 1.0));
-
- crate::tui::clear_area(frame, dl_area, &self.theme);
- frame.render_widget(gauge, dl_area);
+ }
+ } else {
+ row_spans.push(Span::styled(truncated_status, self.theme.subtext1));
}
}
+
+ frame.render_widget(Paragraph::new(Line::from(row_spans)), inner_area);
}
fn draw_theme_picker(&mut self, frame: &mut Frame, area: Rect) {
@@ -1129,3 +1249,70 @@ impl App {
frame.render_widget(popup, inner_area);
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+
+ #[test]
+ fn test_download_bar_rendering_modern_and_basic() {
+ let backend = TestBackend::new(100, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let mut app = App::new();
+ app.state.download_progress = Some(93.2);
+ app.state.download_title = Some("Ek Deewane Ki Deewaniyat".to_string());
+ app.state.download_status = Some("778.6 MB | 4.6 MB/s | ETA 00:12".to_string());
+ app.state.basic_terminal = false;
+ terminal
+ .draw(|f| {
+ app.draw(f);
+ })
+ .unwrap();
+
+ let mut rendered = String::new();
+ for y in 0..24 {
+ for x in 0..100 {
+ let cell = terminal.backend().buffer().cell((x, y)).unwrap();
+ rendered.push_str(cell.symbol());
+ }
+ rendered.push('\n');
+ }
+
+ assert!(rendered.contains("Downloading:"));
+ assert!(rendered.contains("Ek Deewane Ki Deewaniyat"));
+ assert!(rendered.contains("[x] Cancel"));
+ assert!(rendered.contains("93.2%"));
+ assert!(rendered.contains("778.6 MB"));
+ assert!(rendered.contains("4.6 MB/s"));
+ assert!(rendered.contains("ETA 00:12"));
+
+ app.state.basic_terminal = true;
+ terminal
+ .draw(|f| {
+ app.draw(f);
+ })
+ .unwrap();
+
+ let mut basic_rendered = String::new();
+ for y in 0..24 {
+ for x in 0..100 {
+ let cell = terminal.backend().buffer().cell((x, y)).unwrap();
+ basic_rendered.push_str(cell.symbol());
+ }
+ basic_rendered.push('\n');
+ }
+
+ assert!(basic_rendered.contains("[DL]"));
+ assert!(basic_rendered.contains("===="));
+ assert!(basic_rendered.contains("[x] Cancel"));
+
+ let narrow_backend = TestBackend::new(45, 24);
+ let mut narrow_terminal = Terminal::new(narrow_backend).unwrap();
+ let res = narrow_terminal.draw(|f| {
+ app.draw(f);
+ });
+ assert!(res.is_ok());
+ }
+}
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 0f6f9a9..0b5dcdd 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -199,6 +199,7 @@ pub struct PlaybackState {
pub struct DownloadState {
pub download_progress: Option<f64>,
pub download_status: Option<String>,
+ pub download_title: Option<String>,
pub download_dir: Option<std::path::PathBuf>,
pub download_queue_total: usize,
pub show_season_download_confirm: bool,
@@ -330,6 +331,7 @@ pub struct AppState {
pub update_progress_msg: Option<String>,
pub download_progress: Option<f64>,
pub download_status: Option<String>,
+ pub download_title: Option<String>,
pub cancel_download: std::sync::Arc<std::sync::atomic::AtomicBool>,
pub download_dir: Option<std::path::PathBuf>,
@@ -493,6 +495,7 @@ impl Default for AppState {
update_progress_msg: None,
download_progress: None,
download_status: None,
+ download_title: None,
cancel_download: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
download_dir: None,
download_queue: std::collections::VecDeque::new(),