Skip to content

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

fix(tui): polish modal layout, help screen, and 256-color quantization

Samir Hossains6cfb7b07f1a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4674314..f3e43d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,11 +15,82 @@
- **Automatic BDIX Network Availability Probing**:
- Added non-blocking HTTP network probes (`probe_url`) on first application startup with a 3-second timeout against CircleFTP and DhakaFlix endpoints, automatically enabling accessible optical mirrors on local networks while disabling unreachable ones.
- Added a dedicated "Re-check BDIX Network" action in Settings → Maintenance allowing users to manually re-probe and refresh BDIX provider availability at any time.
+- **Watch History Clearing and Item Management**:
+ - Added a dedicated "Clear Watch History" action row in Settings → Maintenance, allowing users to wipe all watch history records and saved playback positions in one action.
+ - Added individual item deletion via `d` and `Delete` keybindings when browsing `/history` results or the Home screen Resume deck, updating disk storage and notifying immediately.
- **Unified Streaming and Stremio Addons Engine**:
- Merged separate Addon Mode into standard Streaming Mode; Stremio Addons (`ProviderKind::Addons`) is now a first-class streaming provider selectable directly via `Ctrl+P`.
- Simplified application state model by removing `AppMode::Addon` and `AppState.is_addon_mode`, making navigation two-mode (`Streaming` and `Live TV`).
- Routed Addon Manager dialog access through `/config` when the active provider is `Addons`.
+- **Theme Color and Contrast Hardening**:
+ - Added typed background and surface color helper methods on `Theme` (`surface0_color`, `surface1_color`, `surface2_color`, `crust_color`, `mantle_color`) extracting underlying foreground colors with graceful `base` fallback.
+ - Replaced hardcoded Catppuccin Mocha RGB values across badge, home screen pill, confirmation modal, and settings input backgrounds with dynamic theme color helpers, ensuring correct contrast across all dark and light themes.
+ - Fixed resolution badge text on active rows to dynamically derive contrast foreground from `theme.crust_color()` rather than hardcoded Mocha crust RGB (`17, 17, 27`).
+ - Fixed inactive modal badge text style from `theme.muted` to `theme.overlay1`, eliminating low-contrast illegibility on `surface1` backgrounds.
+ - Hardened Catppuccin Latte light theme tokens (`sapphire`, `lavender`, `highlight`, `success`, `shortcut`, `rating`, `teal`), achieving WCAG AA contrast (≥4.5:1 on base, ≥3.0:1 on surface1) without sacrificing hue recognition.
+
+- **Terminal Color Quantization and Standard Detection Fixes**:
+ - Fixed `rgb_to_xterm256` color quantization to compute squared Euclidean distance to both the nearest 6×6×6 cube entry and the nearest 24-step grayscale ramp, preventing dark and low-saturation palette backgrounds (such as Mocha base, Nord base, and Dracula base) from crushing to pure black or wrong-hue cube cells on 256-color terminals.
+ - Aligned `NO_COLOR` environment variable checks with the no-color.org specification by checking non-empty values (`is_ok_and(|v| !v.is_empty())`), ensuring empty strings do not disable color support.
+ - Constrained `VTE_VERSION` truecolor capability detection to VTE versions ≥ 3600, correctly identifying older VTE terminals as 256-color rather than truecolor.
+ - Replaced hardcoded fallback colors (`Color::Rgb(69, 71, 90)` and `Color::Rgb(116, 199, 236)` on landing overflow pill, and `Color::White` on details metadata) with dynamic theme palette colors (`theme.base`).
+- **Notification System Overhaul and Adaptive Layout Polish**:
+ - Added instant `Esc` key dismissal for active notification toasts across home and details screens when no popup modals or text input fields are active.
+ - Replaced fixed 3-card stack with terminal dimension-adaptive budgets: compact/Termux displays ($H < 20$ or $W < 65$) show at most 1 toast capped at 42 columns and 1 line of message; standard displays ($H < 30$) show up to 2 toasts capped at 2 lines; large displays show up to 3 toasts.
+ - Added in-place category lifecycle replacement and de-duplication in `state.notify()`: notifications in the same category (e.g. `Playback`, `Download`, `Updates`, `Cache`) or matching title supersede prior in-flight stages and reset the countdown timer rather than spawning redundant stacked cards.
+ - Compressed notification copy into terse, high-density phrasing, ensuring status transitions (e.g. playback prep, favorite toggle, cache clear, updates) fit cleanly into single-line messages without multi-row wrapping.
+- **OS-Aware Header-Capable Player Feedback**:
+ - Replaced hardcoded multi-line player incompatibility warning paragraphs with concise single-line notifications dynamically listing supported header-capable players for the user's OS (`mpv` and `IINA` on macOS; `mpv` on Linux and Windows).
+ - Eliminated speculative hardcoded provider hints in playback rejection notifications.
+- **Help Modal Alignment and Shortcut Declutter**:
+ - Added `help_modal_layout` in `overlay.rs` snapping the Help modal directly to the search bar vertical position (`search_y`), eliminating vertical misalignments where the search bar previously peaked through above or behind the dialog.
+ - Added render suppression in `home.rs` ensuring the search bar, landing deck, and suggestions are completely hidden while Help is active.
+ - Migrated Help dialog rendering to `ModalFrame` with standard backdrop clearing and `theme.lavender` borders, removing redundant manual block construction.
+ - Lowered two-column layout threshold from 102 to 78 columns, enabling clean dual-column layouts on standard 80×24 terminals without scrolling.
+ - Streamlined shortcut descriptions: removed non-existent `[s]` subtitles hotkey, corrected `Ctrl+W` label, eliminated duplicate `/list` command in TV mode, and stripped noisy brackets.
+ - Pruned dead `Theme.bg` field and obsolete `SlashCommand::PRIMARY` array.
+- **Landing Deck Minimalist Declutter (Resume & Favorites)**:
+ - Replaced wordy "Continue Watching" label with concise "Resume" (reducing header width from 34 to 24 characters) and restyled tab navigation with discrete keyhint syntax (`[Tab]`).
+ - Streamlined in-progress watch metadata from redundant triplets (`S01E01 · 5% · 42m left`) to clean time-to-finish tags (`S01E01 · 42m left`), falling back to percentage only when stream duration is absent.
+- **Details Screen UX Polish and Layout Space Reclamation**:
+ - Dynamically capped `selector_height` to the item count of visible selector panes, eliminating excessive empty vertical rows when selector panes have few items.
+ - Dynamically capped `streams_area` height to the exact settled stream count (`streams_count + 3`), eliminating the massive blank dead space below the stream table on titles with few streams.
+ - Formatted Season list items as full descriptive `Season N` labels and Episode list items as `Episode 01 · Title` (or `Episode 01` fallback), ensuring clear context.
+ - Left-aligned data cells in the `SIZE` column to start at index 0, aligning the size value (`1.4GB`) directly beneath the `SIZE` column header.
+ - Added symmetric 1-character horizontal padding (`Padding::horizontal(1)`) to the streams panel container block, preventing text and resolution badges from touching the outer border lines.
+ - Replaced heavy filled `●` focus markers in pane titles with a minimal `›` (single chevron) glyph.
+ - Removed noisy pane position counters (`1/4`) from focused pane titles in favor of clean item count badges (`› Audio (4)`).
+ - Deduplicated `Audio:` metadata badge from the top header line when dedicated dub/audio selector panes are visible below.
+ - Replaced legacy middot (`·`) separators in the header metadata line with clean two-space spacing.
+ - Suppressed missing/N/A release years in the metadata badge row.
+ - Dropped redundant no-op `highlight_style`/`highlight_symbol` calls from selector `List` widgets.
+- **Search Results Layout Top Margin and Metadata Alignment**:
+ - Added dedicated top breathing margin (`search_results_layout`) above the search bar on non-compact viewports (`area.height >= 14`), moving the search bar down from row 0 to row 1 to prevent it hugging the top window border.
+ - Synchronized mouse click geometry in `handle_home_mouse` with `search_results_layout`, keeping search bar and results list hitboxes aligned.
+ - Balanced search result card layout across three vertical rows: Row 1 displays title and resolution badge, Row 2 displays rating, release year, and media type, and Row 3 displays provider badge and genres/loading state.
+ - Aligned all 3 rows of text with the 3 rows of the poster placeholder (`╭──────╮` on Row 1, `│ No Art │` on Row 2, `╰──────╯` on Row 3), eliminating the hanging bottom border and empty-line visual disconnect.
+### Fixed
+- **Details Screen Selector Panes Tight Label Highlighting**:
+ - Replaced wide full-width block highlight bars across Audio, Seasons, and Episodes selector panes with compact, text-bounded highlight pills, eliminating awkward empty horizontal background strips across the lists.
+- **Stream Table Migration to Native Ratatui Table Architecture**:
+ - Replaced legacy dual-widget hack (`Paragraph` header + `List` items) with native `ratatui::widgets::Table` and `Row`/`Cell` primitives, guaranteeing 100% mathematical column synchronization between table headers (`RES`, `SIZE`, `MEDIA TAGS`, `SOURCE`, `RELEASE`) and data cells across every terminal dimension tier.
+ - Replaced wide string space hacks with declarative `Constraint` column widths (`Length(8)`, `Length(9)`, `Length(18)`, `Length(16)`, `Min(24)`), eliminating column drift and text overlap.
+ - Added active-selection awareness to `resolution_badge_spans`: badges render with subtle dark surfaces and theme accent text when unselected, cleanly switching to bold high-contrast foreground badges when the stream row is highlighted. Added automated cross-theme test verifying contrast and legibility across all 9 built-in themes.
+ - Filtered out redundant codec and resolution labels in the `SOURCE` column (e.g. `Multi-Res hevc` or `1080p`), falling back to clean provider origin names (`MovieBox CDN`) when no distinct third-party upload source exists.
+- **Subtitle Episode Mismatch on MovieBox Series**:
+ - `fetch_resource_page` now accepts `season` and `episode` parameters and appends `se=`/`ep=` to the API URL.
+ - Added robust string and integer parsing for `se` and `ep` payload values and matched resource items in `episode_streams` and `service.rs` sibling fallback explicitly by `item.se == season && item.ep == episode` rather than unconditionally taking `.first()`, preventing episode 1 resource IDs from being assigned to later episodes.
+ - Fixed `playback.rs` using `selected_details.id.value` (root series ID) instead of `state.active_subject_id` (dub-aware active ID) as the subject key for caption requests; for dubbed variants the two diverge, causing a cache miss and wrong-subject subtitle fetch.
+ - Updated all call sites (`download.rs`, `requests.rs` prefetch and season-queue spawns, `playback.rs`) to capture and forward the current `selected_season`/`selected_episode` before spawning async subtitle tasks.
+ - Users with pre-existing stale subtitle cache entries can purge old entries via Settings → Maintenance → Purge Cache.
+- **Search Results Horizontal Margin Alignment**:
+ - Aligned search results grid horizontally with `search_bar_area` (`x: chunks[2].x + 2, width: chunks[2].width - 4`), eliminating the awkward 2-character left overhang where result cards previously started flush against the terminal's 0-column border while the search input prompt was indented.
+ - Synchronized mouse hitboxes and column detection in `handle_home_mouse` to match the padded results bounds and ignore out-of-bounds clicks in the margin.
+- **Subtitle Selection Picker Padding and Geometry Optimization**:
+ - Added symmetric 1-character horizontal padding (`Span::raw(" ")`) around raw picker list item spans in `crate::tui::overlay::picker`, ensuring text and active selection pills no longer hug the outer modal borders.
+ - Reduced subtitle picker `minimum_width` from `26` to `20` and unified modal titles to `Subtitles`, eliminating the excessive 10-column dead space gap on the right-hand side while cleanly fitting the `"Subtitles · 1/12"` title without truncation.
+ - Synchronized `minimum_width` constraints across rendering and mouse hitboxes in `mouse.rs` for player (`10`), theme (`16`), and subtitle (`20`) pickers.
- **Provider Selection Popup UX and Layout Unification**:
- Replaced manual paragraph iteration in `render_provider_popup` with `ratatui::widgets::List` and canonical `selection_style`, eliminating competing dual-indicator visuals (left bar and background highlight) into a single cohesive selection cue.
- Added persistent `✓` active provider prefix glyph in `theme.success`, ensuring the currently active source remains visually distinguishable while navigating through options.
diff --git a/docs/controls.md b/docs/controls.md
index f74cbe3..b9c7bf0 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -11,11 +11,11 @@ MovieBox-TUI is designed for fast keyboard navigation with complete mouse suppor
| **`Home` / `End` / `g` / `G`** | Jump to start / end of list or search results (auto-fetches next page), or move cursor to beginning / end of input line |
| **`PageUp` / `PageDown`** | Scroll search results, lists, and modal pickers by visible page height (or scroll help overlay) |
| **`Enter`** | Open, play, or confirm the selected item |
-| **`Space` / `P`** | Direct resume playback for recorded season/episode on `/history` or Home Continue Watching items |
-| **`Esc`** | Focus search input (when results present), dismiss popup dialog, or return to landing |
-| **`Tab` / `Shift+Tab`** | Auto-complete suggestion / command; cycle landing deck tabs (Continue Watching / Favorites); switch details panes; toggle dialog buttons |
+| **`Space` / `P`** | Direct resume playback for recorded season/episode on `/history` or Home Resume items |
+| **`Esc`** | Dismiss active notifications, focus search input (when results present), dismiss popup dialog, or return to landing |
+| **`Tab` / `Shift+Tab`** | Auto-complete suggestion / command; cycle landing deck tabs (Resume / Favorites); switch details panes; toggle dialog buttons |
| **`Backspace`** | Delete character before cursor, or return focus to search bar from results |
-| **`Delete`** | Delete character at cursor in text inputs, or remove entry in TV/Addon managers |
+| **`d` / `Delete`** | Delete character at cursor in text inputs; remove selected entry in `/history`, Home Resume deck, or TV/Addon managers |
| **`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) |
@@ -87,9 +87,9 @@ All popup dialogs (Theme picker, Browse categories, Provider menu, Settings Medi
| **Click provider badge** | Open anchored provider selection menu; click provider to switch directly |
| **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 landing deck tab header** | Switch between Resume 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 Resume 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 |
| **Click audio / season / episode / stream** | Switch audio language, change season, or select episode; click a specific stream row to play; click empty stream pane space to focus without playing |
diff --git a/docs/players.md b/docs/players.md
index fddc52e..78f1e7d 100644
--- a/docs/players.md
+++ b/docs/players.md
@@ -32,7 +32,7 @@ Playback sources (for example 4KHD and MovieBox) may carry `Referer`/`User-Agent
MovieBox DASH streams additionally carry signed `Cookie` headers for CloudFront authentication.
mpv/IINA send them via `http-header-fields` (`--http-header-fields=...` or `--mpv-http-header-fields=...`),
while VLC maps them to `--http-referrer` / `--http-user-agent`. Android intent playback forwards `Referer`/`User-Agent` extras when using `am`/`termux-am`, and supports unauthenticated streams (CircleFTP, DhakaFlix, IPTV) and CDN streams natively.
-The `supports_headers` gate in `app/playback.rs` validates whether a player can satisfy required stream headers. MovieBox-TUI strictly respects the user's configured default player: if the chosen player cannot satisfy a stream's headers (such as VLC or Android Player attempting to play signed MovieBox DASH manifests with CloudFront cookie requirements), playback will not silently fall back to an alternative player. Instead, an explicit warning notification informs the user of the exact incompatibility and lists available compatible alternatives (e.g. mpv) or the option to switch providers with `Ctrl+P`.
+The `supports_headers` gate in `app/playback.rs` validates whether a player can satisfy required stream headers. MovieBox-TUI strictly respects the user's configured default player: if the chosen player cannot satisfy a stream's headers (such as VLC or Android Player attempting to play signed MovieBox DASH manifests with CloudFront cookie requirements), playback will not silently fall back to an alternative player. Instead, an explicit warning notification informs the user of the lack of header support, prompting them to switch to a supported player or install one for their operating system (`mpv` and `IINA` on macOS; `mpv` on Linux and Windows).
## Subtitles
- mpv receives the remote subtitle URL directly (`--sub-file=<url>`); mpv fetches it
diff --git a/src/player.rs b/src/player.rs
index 5b38f83..6835b68 100644
--- a/src/player.rs
+++ b/src/player.rs
@@ -82,6 +82,17 @@ pub fn supports_headers(kind: PlayerKind, headers: &[(String, String)]) -> bool
}
}
+pub fn header_capable_players() -> &'static [PlayerKind] {
+ #[cfg(target_os = "macos")]
+ {
+ &[PlayerKind::Mpv, PlayerKind::Iina]
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ &[PlayerKind::Mpv]
+ }
+}
+
pub fn command(
kind: PlayerKind,
url: &str,
diff --git a/src/providers/moviebox/mod.rs b/src/providers/moviebox/mod.rs
index 313d1f1..a437006 100644
--- a/src/providers/moviebox/mod.rs
+++ b/src/providers/moviebox/mod.rs
@@ -63,14 +63,39 @@ impl crate::providers::ReleaseProvider for client::MovieBoxClient {
) -> Result<Vec<crate::providers::models::Release>, ProviderError> {
let (play_info_res, resources_res) = tokio::join!(
self.get_play_info(id, season, episode),
- self.get_resources(id, season, episode, 1, None, 5)
+ self.get_resources(
+ id,
+ season,
+ episode,
+ if episode > 0 {
+ (episode - 1) / 20 + 1
+ } else {
+ 1
+ },
+ None,
+ 20,
+ )
);
-
let upload_resource_id = resources_res.ok().and_then(|val| {
val.get("list")
.or_else(|| val.get("data").and_then(|d| d.get("list")))
.and_then(|l| l.as_array())
- .and_then(|arr| arr.first())
+ .and_then(|arr| {
+ arr.iter().find(|item| {
+ let parse_num = |k: &str| -> Option<usize> {
+ item.get(k).and_then(|v| {
+ v.as_u64()
+ .map(|n| n as usize)
+ .or_else(|| v.as_i64().map(|n| n as usize))
+ .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
+ })
+ };
+ let se = parse_num("se");
+ let ep_num = parse_num("ep");
+ (season == 0 && episode == 0)
+ || (se == Some(season) && ep_num == Some(episode))
+ })
+ })
.and_then(|item| {
item.get("resourceId")
.or_else(|| item.get("id"))
@@ -99,8 +124,13 @@ impl crate::providers::ReleaseProvider for client::MovieBoxClient {
return Ok(releases);
}
+ let page = if episode > 0 {
+ (episode - 1) / 20 + 1
+ } else {
+ 1
+ };
let (items, _) = self
- .fetch_resource_page(id, 0, 1)
+ .fetch_resource_page(id, season, episode, 0, page)
.await
.map_err(ProviderError::from)?;
let mut legacy_releases = Vec::new();
@@ -226,19 +256,12 @@ impl MovieBoxClient {
pub async fn fetch_resource_page(
&self,
subject_id: &str,
+ season: usize,
+ episode: usize,
resolution: u32,
page: usize,
) -> Result<(Vec<Value>, Value), ScraperError> {
- let res_param = if resolution == 0 {
- String::new()
- } else {
- format!("&resolution={}", resolution)
- };
-
- let path = format!(
- "/wefeed-mobile-bff/subject-api/resource?subjectId={}&page={}&perPage=20{}",
- subject_id, page, res_param
- );
+ let path = resource_page_path(subject_id, season, episode, resolution, page);
let res = self.get(&path).await?;
@@ -307,3 +330,61 @@ impl MovieBoxClient {
self.get(&path).await
}
}
+
+pub fn resource_page_path(
+ subject_id: &str,
+ season: usize,
+ episode: usize,
+ resolution: u32,
+ page: usize,
+) -> String {
+ let res_param = if resolution == 0 {
+ String::new()
+ } else {
+ format!("&resolution={}", resolution)
+ };
+
+ if season == 0 && episode == 0 {
+ format!(
+ "/wefeed-mobile-bff/subject-api/resource?subjectId={}&page={}&perPage=20{}",
+ subject_id, page, res_param
+ )
+ } else {
+ format!(
+ "/wefeed-mobile-bff/subject-api/resource?subjectId={}&se={}&ep={}&page={}&perPage=20{}",
+ subject_id, season, episode, page, res_param
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_resource_page_path_movie() {
+ let path = resource_page_path("12345", 0, 0, 0, 1);
+ assert_eq!(
+ path,
+ "/wefeed-mobile-bff/subject-api/resource?subjectId=12345&page=1&perPage=20"
+ );
+ }
+
+ #[test]
+ fn test_resource_page_path_series_with_se_and_ep() {
+ let path = resource_page_path("67890", 2, 5, 0, 1);
+ assert_eq!(
+ path,
+ "/wefeed-mobile-bff/subject-api/resource?subjectId=67890&se=2&ep=5&page=1&perPage=20"
+ );
+ }
+
+ #[test]
+ fn test_resource_page_path_with_resolution() {
+ let path = resource_page_path("67890", 1, 10, 1080, 2);
+ assert_eq!(
+ path,
+ "/wefeed-mobile-bff/subject-api/resource?subjectId=67890&se=1&ep=10&page=2&perPage=20&resolution=1080"
+ );
+ }
+}
diff --git a/src/service.rs b/src/service.rs
index 1e684dd..2b11bee 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -195,6 +195,8 @@ impl MovieBoxService {
subject_id: &str,
resource_id: &str,
sibling_ids: &[String],
+ season: usize,
+ episode: usize,
) -> Result<Vec<crate::providers::models::SubtitleOption>, String> {
let mut all_captions = Vec::new();
let mut seen_urls = std::collections::HashSet::new();
@@ -213,8 +215,10 @@ impl MovieBoxService {
if !sib.is_empty() && sib != subject_id {
let client = &self.client;
sibling_futs.push(async move {
- if let Ok((items, _)) = client.fetch_resource_page(sib, 0, 1).await {
- if let Some(item) = items.first() {
+ let page = if episode > 0 { (episode - 1) / 20 + 1 } else { 1 };
+ if let Ok((items, _)) = client.fetch_resource_page(sib, season, episode, 0, page).await {
+ let matched_item = find_matching_resource_item(&items, season, episode);
+ if let Some(item) = matched_item {
let item_rid = item
.get("resourceId")
.or_else(|| item.get("id"))
@@ -283,7 +287,6 @@ impl MovieBoxService {
}
}
}
-
pub async fn fetch_poster_bytes(&self, url: &str) -> Option<Vec<u8>> {
let response = self
.http_client
@@ -468,6 +471,26 @@ pub fn resolve_download_dir(custom_dir: Option<&Path>) -> PathBuf {
ensure_moviebox_subdir(&base_dir)
}
+pub fn find_matching_resource_item(
+ items: &[serde_json::Value],
+ season: usize,
+ episode: usize,
+) -> Option<&serde_json::Value> {
+ items.iter().find(|item| {
+ let parse_num = |k: &str| -> Option<usize> {
+ item.get(k).and_then(|v| {
+ v.as_u64()
+ .map(|n| n as usize)
+ .or_else(|| v.as_i64().map(|n| n as usize))
+ .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
+ })
+ };
+ let se = parse_num("se");
+ let ep_num = parse_num("ep");
+ (season == 0 && episode == 0) || (se == Some(season) && ep_num == Some(episode))
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -485,4 +508,62 @@ mod tests {
assert_eq!(decoded.width(), 512);
assert_eq!(decoded.height(), 384);
}
+
+ #[test]
+ fn test_find_matching_resource_item_integer_and_string_values() {
+ let items = vec![
+ serde_json::json!({
+ "id": "1001",
+ "se": 1,
+ "ep": 1
+ }),
+ serde_json::json!({
+ "id": "1002",
+ "se": "2",
+ "ep": "5"
+ }),
+ ];
+
+ let matched = find_matching_resource_item(&items, 2, 5);
+ assert!(matched.is_some());
+ assert_eq!(matched.unwrap().get("id").unwrap().as_str(), Some("1002"));
+ }
+
+ #[test]
+ fn test_find_matching_resource_item_series_does_not_fall_back_to_episode_one() {
+ let items = vec![
+ serde_json::json!({
+ "id": "1001",
+ "se": 1,
+ "ep": 1
+ }),
+ serde_json::json!({
+ "id": "1002",
+ "se": 1,
+ "ep": 2
+ }),
+ ];
+
+ let matched = find_matching_resource_item(&items, 2, 3);
+ assert!(matched.is_none());
+ }
+
+ #[test]
+ fn test_find_matching_resource_item_movie_matches_first() {
+ let items = vec![
+ serde_json::json!({
+ "id": "movie_res_1"
+ }),
+ serde_json::json!({
+ "id": "movie_res_2"
+ }),
+ ];
+
+ let matched = find_matching_resource_item(&items, 0, 0);
+ assert!(matched.is_some());
+ assert_eq!(
+ matched.unwrap().get("id").unwrap().as_str(),
+ Some("movie_res_1")
+ );
+ }
}
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index b98c16c..ffcab2a 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -597,9 +597,11 @@ impl App {
ids
})
.unwrap_or_default();
+ let season = self.state.selected_season;
+ let episode = self.state.selected_episode;
tokio::spawn(async move {
if let Ok(res) = service
- .get_ext_captions(&subject_id, &rid, &sibling_ids)
+ .get_ext_captions(&subject_id, &rid, &sibling_ids, season, episode)
.await
{
sender.send(Action::ShowDownloadSubtitlePopup(res)).ok();
diff --git a/src/tui/app/favorites.rs b/src/tui/app/favorites.rs
index 5b618a5..ade6dd5 100644
--- a/src/tui/app/favorites.rs
+++ b/src/tui/app/favorites.rs
@@ -128,9 +128,9 @@ impl App {
},
"Favorites",
if now_favorited {
- format!("Added \"{title}\" to Favorites.")
+ format!("Added: {title}")
} else {
- format!("Removed \"{title}\" from Favorites.")
+ format!("Removed: {title}")
},
);
}
@@ -268,7 +268,7 @@ impl App {
self.state.notify(
NotificationKind::Info,
"Favorites",
- "No favorites yet. Favorite a title with 'f' to add one.",
+ "No favorites yet (add with 'f')",
);
} else {
items.sort_by_key(|item| std::cmp::Reverse(item.added_at));
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 2e6a74a..4637622 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -98,7 +98,7 @@ impl App {
self.state.notify(
crate::tui::overlay::NotificationKind::Info,
"Homebrew Upgrade",
- "Run 'brew upgrade moviebox-tui' in your terminal to update.",
+ "Run: brew upgrade moviebox-tui",
);
self.state.update_available = None;
return None;
@@ -662,206 +662,213 @@ impl App {
_ => {}
}
}
- InputMode::Normal => match self.state.active_screen {
- Screen::Home => {
- if self.state.addon_manager_popup {
- if self.state.addon_input_active {
+ InputMode::Normal => {
+ match self.state.active_screen {
+ Screen::Home => {
+ if self.state.addon_manager_popup {
+ if self.state.addon_input_active {
+ match key.code {
+ KeyCode::Esc => {
+ self.state.addon_input_active = false;
+ self.state.addon_input_buffer.clear();
+ }
+ KeyCode::Enter => {
+ let buffer = self
+ .state
+ .addon_input_buffer
+ .as_str()
+ .trim()
+ .to_string();
+ self.state.addon_input_active = false;
+ self.state.addon_input_buffer.clear();
+ if !buffer.is_empty() {
+ self.action_sender
+ .send(Action::AddonAddManifest(buffer))
+ .ok();
+ }
+ }
+ KeyCode::Left => {
+ self.state.addon_input_buffer.move_left();
+ }
+ KeyCode::Right => {
+ self.state.addon_input_buffer.move_right();
+ }
+ KeyCode::Home => {
+ self.state.addon_input_buffer.move_home();
+ }
+ KeyCode::End => {
+ self.state.addon_input_buffer.move_end();
+ }
+ KeyCode::Backspace => {
+ self.state.addon_input_buffer.delete_backwards();
+ }
+ KeyCode::Delete => {
+ self.state.addon_input_buffer.delete_forwards();
+ }
+ KeyCode::Char('u') | KeyCode::Char('U')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ self.state.addon_input_buffer.clear();
+ }
+ KeyCode::Char('w') | KeyCode::Char('W')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ self.state.addon_input_buffer.delete_word_backwards();
+ }
+ KeyCode::Char(c) if !c.is_control() => {
+ self.state.addon_input_buffer.insert(c);
+ }
+ _ => {}
+ }
+ return None;
+ }
match key.code {
KeyCode::Esc => {
- self.state.addon_input_active = false;
- self.state.addon_input_buffer.clear();
+ self.reset_transient_overlays();
+ self.state.addon_manager_popup = false;
}
- KeyCode::Enter => {
- let buffer =
- self.state.addon_input_buffer.as_str().trim().to_string();
- self.state.addon_input_active = false;
- self.state.addon_input_buffer.clear();
- if !buffer.is_empty() {
- self.action_sender
- .send(Action::AddonAddManifest(buffer))
- .ok();
- }
+ KeyCode::Up => {
+ self.state.step_addon_manager_selected(-1);
}
- KeyCode::Left => {
- self.state.addon_input_buffer.move_left();
- }
- KeyCode::Right => {
- self.state.addon_input_buffer.move_right();
+ KeyCode::Down => {
+ self.state.step_addon_manager_selected(1);
}
KeyCode::Home => {
- self.state.addon_input_buffer.move_home();
+ self.state.first_addon_manager_selected();
}
KeyCode::End => {
- self.state.addon_input_buffer.move_end();
- }
- KeyCode::Backspace => {
- self.state.addon_input_buffer.delete_backwards();
+ self.state.last_addon_manager_selected();
}
- KeyCode::Delete => {
- self.state.addon_input_buffer.delete_forwards();
+ KeyCode::PageUp => {
+ self.state.step_addon_manager_selected(-5);
}
- KeyCode::Char('u') | KeyCode::Char('U')
- if key
- .modifiers
- .contains(crossterm::event::KeyModifiers::CONTROL) =>
- {
- self.state.addon_input_buffer.clear();
+ KeyCode::PageDown => {
+ self.state.step_addon_manager_selected(5);
}
- KeyCode::Char('w') | KeyCode::Char('W')
- if key
- .modifiers
- .contains(crossterm::event::KeyModifiers::CONTROL) =>
- {
- self.state.addon_input_buffer.delete_word_backwards();
+ KeyCode::Char('d') | KeyCode::Delete => {
+ use crate::tui::state::AddonManagerRow;
+ if let Some(AddonManagerRow::Addon(index)) = self
+ .state
+ .addon_manager_rows()
+ .get(self.state.addon_manager_selected)
+ .copied()
+ {
+ self.action_sender.send(Action::AddonRemove(index)).ok();
+ }
}
- KeyCode::Char(c) if !c.is_control() => {
- self.state.addon_input_buffer.insert(c);
+ KeyCode::Enter | KeyCode::Char(' ') => {
+ self.addon_manager_activate();
}
_ => {}
}
return None;
}
- match key.code {
- KeyCode::Esc => {
- self.reset_transient_overlays();
- self.state.addon_manager_popup = false;
- }
- KeyCode::Up => {
- self.state.step_addon_manager_selected(-1);
- }
- KeyCode::Down => {
- self.state.step_addon_manager_selected(1);
- }
- KeyCode::Home => {
- self.state.first_addon_manager_selected();
- }
- KeyCode::End => {
- self.state.last_addon_manager_selected();
- }
- KeyCode::PageUp => {
- self.state.step_addon_manager_selected(-5);
- }
- KeyCode::PageDown => {
- self.state.step_addon_manager_selected(5);
- }
- KeyCode::Char('d') | KeyCode::Delete => {
- use crate::tui::state::AddonManagerRow;
- if let Some(AddonManagerRow::Addon(index)) = self
- .state
- .addon_manager_rows()
- .get(self.state.addon_manager_selected)
- .copied()
- {
- self.action_sender.send(Action::AddonRemove(index)).ok();
+
+ if self.state.tv_config_popup {
+ if self.state.tv_input_active {
+ match key.code {
+ KeyCode::Esc => {
+ self.state.tv_input_active = false;
+ self.state.tv_input_buffer.clear();
+ }
+ KeyCode::Enter => {
+ let buffer =
+ self.state.tv_input_buffer.as_str().trim().to_string();
+ self.state.tv_input_active = false;
+ self.state.tv_input_buffer.clear();
+ if !buffer.is_empty() {
+ self.action_sender
+ .send(Action::TvPlaylistAdd(buffer))
+ .ok();
+ }
+ }
+ KeyCode::Left => {
+ self.state.tv_input_buffer.move_left();
+ }
+ KeyCode::Right => {
+ self.state.tv_input_buffer.move_right();
+ }
+ KeyCode::Home => {
+ self.state.tv_input_buffer.move_home();
+ }
+ KeyCode::End => {
+ self.state.tv_input_buffer.move_end();
+ }
+ KeyCode::Backspace => {
+ self.state.tv_input_buffer.delete_backwards();
+ }
+ KeyCode::Delete => {
+ self.state.tv_input_buffer.delete_forwards();
+ }
+ KeyCode::Char('u') | KeyCode::Char('U')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ self.state.tv_input_buffer.clear();
+ }
+ KeyCode::Char('w') | KeyCode::Char('W')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ self.state.tv_input_buffer.delete_word_backwards();
+ }
+ KeyCode::Char(c) if !c.is_control() => {
+ self.state.tv_input_buffer.insert(c);
+ }
+ _ => {}
}
+ return None;
}
- KeyCode::Enter | KeyCode::Char(' ') => {
- self.addon_manager_activate();
- }
- _ => {}
- }
- return None;
- }
-
- if self.state.tv_config_popup {
- if self.state.tv_input_active {
match key.code {
KeyCode::Esc => {
- self.state.tv_input_active = false;
- self.state.tv_input_buffer.clear();
- }
- KeyCode::Enter => {
- let buffer =
- self.state.tv_input_buffer.as_str().trim().to_string();
- self.state.tv_input_active = false;
- self.state.tv_input_buffer.clear();
- if !buffer.is_empty() {
- self.action_sender.send(Action::TvPlaylistAdd(buffer)).ok();
- }
+ self.reset_transient_overlays();
+ self.state.tv_config_popup = false;
}
- KeyCode::Left => {
- self.state.tv_input_buffer.move_left();
+ KeyCode::Up => {
+ self.state.step_tv_manager_selected(-1);
}
- KeyCode::Right => {
- self.state.tv_input_buffer.move_right();
+ KeyCode::Down => {
+ self.state.step_tv_manager_selected(1);
}
KeyCode::Home => {
- self.state.tv_input_buffer.move_home();
+ self.state.first_tv_manager_selected();
}
KeyCode::End => {
- self.state.tv_input_buffer.move_end();
+ self.state.last_tv_manager_selected();
}
- KeyCode::Backspace => {
- self.state.tv_input_buffer.delete_backwards();
+ KeyCode::PageUp => {
+ self.state.step_tv_manager_selected(-5);
}
- KeyCode::Delete => {
- self.state.tv_input_buffer.delete_forwards();
+ KeyCode::PageDown => {
+ self.state.step_tv_manager_selected(5);
}
- KeyCode::Char('u') | KeyCode::Char('U')
- if key
- .modifiers
- .contains(crossterm::event::KeyModifiers::CONTROL) =>
- {
- self.state.tv_input_buffer.clear();
- }
- KeyCode::Char('w') | KeyCode::Char('W')
- if key
- .modifiers
- .contains(crossterm::event::KeyModifiers::CONTROL) =>
- {
- self.state.tv_input_buffer.delete_word_backwards();
+ KeyCode::Char('d') | KeyCode::Delete => {
+ use crate::tui::state::TvManagerRow;
+ if let Some(TvManagerRow::Playlist(index)) = self
+ .state
+ .tv_manager_rows()
+ .get(self.state.tv_manager_selected)
+ .copied()
+ {
+ self.action_sender
+ .send(Action::TvPlaylistRemove(index))
+ .ok();
+ }
}
- KeyCode::Char(c) if !c.is_control() => {
- self.state.tv_input_buffer.insert(c);
+ KeyCode::Enter | KeyCode::Char(' ') => {
+ self.tv_manager_activate();
}
_ => {}
}
return None;
}
match key.code {
- KeyCode::Esc => {
- self.reset_transient_overlays();
- self.state.tv_config_popup = false;
- }
- KeyCode::Up => {
- self.state.step_tv_manager_selected(-1);
- }
- KeyCode::Down => {
- self.state.step_tv_manager_selected(1);
- }
- KeyCode::Home => {
- self.state.first_tv_manager_selected();
- }
- KeyCode::End => {
- self.state.last_tv_manager_selected();
- }
- KeyCode::PageUp => {
- self.state.step_tv_manager_selected(-5);
- }
- KeyCode::PageDown => {
- self.state.step_tv_manager_selected(5);
- }
- KeyCode::Char('d') | KeyCode::Delete => {
- use crate::tui::state::TvManagerRow;
- if let Some(TvManagerRow::Playlist(index)) = self
- .state
- .tv_manager_rows()
- .get(self.state.tv_manager_selected)
- .copied()
- {
- self.action_sender
- .send(Action::TvPlaylistRemove(index))
- .ok();
- }
- }
- KeyCode::Enter | KeyCode::Char(' ') => {
- self.tv_manager_activate();
- }
- _ => {}
- }
- return None;
- }
- match key.code {
KeyCode::Esc => {
self.action_sender.send(Action::GoBack).ok();
}
@@ -1016,6 +1023,75 @@ impl App {
{
self.action_sender.send(Action::ToggleFavorite).ok();
}
+ KeyCode::Char('d') | KeyCode::Char('D') | KeyCode::Delete
+ if (self
+ .state
+ .search_query
+ .trim()
+ .eq_ignore_ascii_case("/history")
+ && !self.state.search_results.is_empty())
+ || (self.state.favorites_focus
+ && self.state.effective_home_deck_tab()
+ == crate::tui::state::HomeDeckTab::ContinueWatching) =>
+ {
+ if self.state.favorites_focus {
+ if let Some(idx) = self.state.favorites_landing_state.selected() {
+ let target = self
+ .state
+ .continue_watching_items()
+ .get(idx)
+ .map(|item| {
+ (
+ item.title.clone(),
+ item.provider.clone(),
+ item.subject_id.clone(),
+ item.season,
+ item.episode,
+ )
+ });
+ if let Some((title, provider, subject_id, season, episode)) = target {
+ self.state.history.remove(&provider, &subject_id, season, episode);
+ self.state.homepage_cache.clear();
+ let total = self.state.landing_deck_items_count();
+ if total == 0 {
+ self.state.favorites_focus = false;
+ self.state.favorites_landing_state.select(None);
+ } else if idx >= total {
+ self.state.favorites_landing_state.select(Some(total.saturating_sub(1)));
+ }
+ self.state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "History",
+ format!("Removed: {title}"),
+ );
+ }
+ }
+ } else if let Some(idx) = self.state.search_list_state.selected() {
+ if idx < self.state.search_results.len() {
+ let res = self.state.search_results.remove(idx);
+ let provider_key = res.provider.cache_key();
+ self.state.history.remove(provider_key, &res.id, res.season, res.episode);
+ self.state.history.recent.retain(|i| {
+ !(i.subject_id == res.id
+ && (crate::providers::models::ProviderKind::parse(&i.provider) == Some(res.provider)
+ || i.provider.eq_ignore_ascii_case(provider_key)))
+ });
+ self.state.history.save();
+ self.state.homepage_cache.clear();
+ let total = self.state.search_results.len();
+ if total == 0 {
+ self.state.search_list_state.select(None);
+ } else if idx >= total {
+ self.state.search_list_state.select(Some(total.saturating_sub(1)));
+ }
+ self.state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "History",
+ format!("Removed: {}", res.title),
+ );
+ }
+ }
+ }
KeyCode::Char(' ') | KeyCode::Char('p') | KeyCode::Char('P')
if (self
.state
@@ -1056,180 +1132,186 @@ impl App {
}
_ => {}
}
- }
- Screen::Details => match key.code {
- KeyCode::Tab => {
- if self.state.show_season_download_confirm {
- self.state.season_download_confirm_yes_selected =
- !self.state.season_download_confirm_yes_selected;
- } else if self.state.show_episode_download_confirm {
- self.state.episode_download_confirm_yes_selected =
- !self.state.episode_download_confirm_yes_selected;
- } else if !self.state.subtitle_popup && !self.state.player_picker_popup {
- self.action_sender.send(Action::TabPane).ok();
- }
}
- KeyCode::BackTab => {
- if self.state.show_season_download_confirm {
- self.state.season_download_confirm_yes_selected =
- !self.state.season_download_confirm_yes_selected;
- } else if self.state.show_episode_download_confirm {
- self.state.episode_download_confirm_yes_selected =
- !self.state.episode_download_confirm_yes_selected;
- } else if !self.state.subtitle_popup && !self.state.player_picker_popup {
- self.action_sender.send(Action::BackTabPane).ok();
+ Screen::Details => match key.code {
+ KeyCode::Tab => {
+ if self.state.show_season_download_confirm {
+ self.state.season_download_confirm_yes_selected =
+ !self.state.season_download_confirm_yes_selected;
+ } else if self.state.show_episode_download_confirm {
+ self.state.episode_download_confirm_yes_selected =
+ !self.state.episode_download_confirm_yes_selected;
+ } else if !self.state.subtitle_popup && !self.state.player_picker_popup
+ {
+ self.action_sender.send(Action::TabPane).ok();
+ }
}
- }
- KeyCode::Char('y') | KeyCode::Char('Y') => {
- if self.state.show_season_download_confirm {
- self.action_sender.send(Action::ConfirmDownloadSeason).ok();
- } else if self.state.show_episode_download_confirm {
- self.action_sender.send(Action::ConfirmDownloadEpisode).ok();
+ KeyCode::BackTab => {
+ if self.state.show_season_download_confirm {
+ self.state.season_download_confirm_yes_selected =
+ !self.state.season_download_confirm_yes_selected;
+ } else if self.state.show_episode_download_confirm {
+ self.state.episode_download_confirm_yes_selected =
+ !self.state.episode_download_confirm_yes_selected;
+ } else if !self.state.subtitle_popup && !self.state.player_picker_popup
+ {
+ self.action_sender.send(Action::BackTabPane).ok();
+ }
}
- }
- KeyCode::Char('n') | KeyCode::Char('N') => {
- if self.state.show_season_download_confirm {
- self.state.show_season_download_confirm = false;
- } else if self.state.show_episode_download_confirm {
- self.state.show_episode_download_confirm = false;
+ KeyCode::Char('y') | KeyCode::Char('Y') => {
+ if self.state.show_season_download_confirm {
+ self.action_sender.send(Action::ConfirmDownloadSeason).ok();
+ } else if self.state.show_episode_download_confirm {
+ self.action_sender.send(Action::ConfirmDownloadEpisode).ok();
+ }
}
- }
- KeyCode::Esc => {
- if self.state.show_season_download_confirm {
- self.state.show_season_download_confirm = false;
- } else if self.state.show_episode_download_confirm {
- self.state.show_episode_download_confirm = false;
- } else {
- self.action_sender.send(Action::GoBack).ok();
+ KeyCode::Char('n') | KeyCode::Char('N') => {
+ if self.state.show_season_download_confirm {
+ self.state.show_season_download_confirm = false;
+ } else if self.state.show_episode_download_confirm {
+ self.state.show_episode_download_confirm = false;
+ }
}
- }
- KeyCode::Char(' ') | KeyCode::Char('p') | KeyCode::Char('P') => {
- if !self.state.subtitle_popup
- && !self.state.player_picker_popup
- && !self.state.show_season_download_confirm
- && !self.state.show_episode_download_confirm
- {
- match self.state.details_pane {
- crate::tui::state::DetailsPane::Streams => {
- self.action_sender.send(Action::PlayStream).ok();
- }
- crate::tui::state::DetailsPane::Seasons => {
- self.trigger_episode_fetch();
- }
- crate::tui::state::DetailsPane::Episodes => {
- self.trigger_episode_fetch();
+ KeyCode::Esc => {
+ if self.state.show_season_download_confirm {
+ self.state.show_season_download_confirm = false;
+ } else if self.state.show_episode_download_confirm {
+ self.state.show_episode_download_confirm = false;
+ } else {
+ self.action_sender.send(Action::GoBack).ok();
+ }
+ }
+ KeyCode::Char(' ') | KeyCode::Char('p') | KeyCode::Char('P') => {
+ if !self.state.subtitle_popup
+ && !self.state.player_picker_popup
+ && !self.state.show_season_download_confirm
+ && !self.state.show_episode_download_confirm
+ {
+ match self.state.details_pane {
+ crate::tui::state::DetailsPane::Streams => {
+ self.action_sender.send(Action::PlayStream).ok();
+ }
+ crate::tui::state::DetailsPane::Seasons => {
+ self.trigger_episode_fetch();
+ }
+ crate::tui::state::DetailsPane::Episodes => {
+ self.trigger_episode_fetch();
+ }
+ crate::tui::state::DetailsPane::Languages => {
+ let idx =
+ self.state.language_list_state.selected().unwrap_or(0);
+ self.action_sender.send(Action::SelectLanguage(idx)).ok();
+ }
}
- crate::tui::state::DetailsPane::Languages => {
- let idx =
- self.state.language_list_state.selected().unwrap_or(0);
- self.action_sender.send(Action::SelectLanguage(idx)).ok();
+ }
+ }
+ KeyCode::Char('q') | KeyCode::Char('Q') => {
+ self.action_sender.send(Action::Quit).ok();
+ }
+ KeyCode::Char('d') | KeyCode::Char('D') => {
+ if !self.state.subtitle_popup && !self.state.player_picker_popup {
+ if let crate::tui::state::DetailsPane::Seasons =
+ self.state.details_pane
+ {
+ if !self.state.available_seasons.is_empty() {
+ self.action_sender.send(Action::PromptDownloadSeason).ok();
+ }
+ } else {
+ self.action_sender.send(Action::PromptDownloadEpisode).ok();
}
}
}
- }
- KeyCode::Char('q') | KeyCode::Char('Q') => {
- self.action_sender.send(Action::Quit).ok();
- }
- KeyCode::Char('d') | KeyCode::Char('D') => {
- if !self.state.subtitle_popup && !self.state.player_picker_popup {
- if let crate::tui::state::DetailsPane::Seasons = self.state.details_pane
+ KeyCode::Char('r') => {
+ if !self.state.subtitle_popup
+ && !self.state.player_picker_popup
+ && !self.state.show_season_download_confirm
+ && !self.state.show_episode_download_confirm
{
- if !self.state.available_seasons.is_empty() {
- self.action_sender.send(Action::PromptDownloadSeason).ok();
- }
- } else {
- self.action_sender.send(Action::PromptDownloadEpisode).ok();
+ self.action_sender.send(Action::Refresh).ok();
}
}
- }
- KeyCode::Char('r') => {
- if !self.state.subtitle_popup
- && !self.state.player_picker_popup
- && !self.state.show_season_download_confirm
- && !self.state.show_episode_download_confirm
- {
- self.action_sender.send(Action::Refresh).ok();
+ KeyCode::Char('?') => {
+ self.action_sender.send(Action::ToggleHelp).ok();
}
- }
- KeyCode::Char('?') => {
- self.action_sender.send(Action::ToggleHelp).ok();
- }
- KeyCode::Char('f') | KeyCode::Char('F') => {
- if !self.state.subtitle_popup
- && !self.state.player_picker_popup
- && !self.state.show_season_download_confirm
- && !self.state.show_episode_download_confirm
- && self.state.favorites_available()
- {
- self.action_sender.send(Action::ToggleFavorite).ok();
+ KeyCode::Char('f') | KeyCode::Char('F') => {
+ if !self.state.subtitle_popup
+ && !self.state.player_picker_popup
+ && !self.state.show_season_download_confirm
+ && !self.state.show_episode_download_confirm
+ && self.state.favorites_available()
+ {
+ self.action_sender.send(Action::ToggleFavorite).ok();
+ }
}
- }
- KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
- self.action_sender.send(Action::MoveUp).ok();
- }
- KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {
- self.action_sender.send(Action::MoveDown).ok();
- }
- KeyCode::Left | KeyCode::Char('h') | KeyCode::Char('H') => {
- if self.state.show_season_download_confirm {
- self.state.season_download_confirm_yes_selected = true;
- } else if self.state.show_episode_download_confirm {
- self.state.episode_download_confirm_yes_selected = true;
- } else if !self.state.subtitle_popup && !self.state.player_picker_popup {
- self.action_sender.send(Action::BackTabPane).ok();
+ KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
+ self.action_sender.send(Action::MoveUp).ok();
}
- }
- KeyCode::Right | KeyCode::Char('l') | KeyCode::Char('L') => {
- if self.state.show_season_download_confirm {
- self.state.season_download_confirm_yes_selected = false;
- } else if self.state.show_episode_download_confirm {
- self.state.episode_download_confirm_yes_selected = false;
- } else if !self.state.subtitle_popup && !self.state.player_picker_popup {
- self.action_sender.send(Action::TabPane).ok();
+ KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {
+ self.action_sender.send(Action::MoveDown).ok();
}
- }
- KeyCode::Enter => {
- if self.state.show_season_download_confirm {
- if self.state.season_download_confirm_yes_selected {
- self.action_sender.send(Action::ConfirmDownloadSeason).ok();
- } else {
- self.state.show_season_download_confirm = false;
+ KeyCode::Left | KeyCode::Char('h') | KeyCode::Char('H') => {
+ if self.state.show_season_download_confirm {
+ self.state.season_download_confirm_yes_selected = true;
+ } else if self.state.show_episode_download_confirm {
+ self.state.episode_download_confirm_yes_selected = true;
+ } else if !self.state.subtitle_popup && !self.state.player_picker_popup
+ {
+ self.action_sender.send(Action::BackTabPane).ok();
}
- } else if self.state.show_episode_download_confirm {
- if self.state.episode_download_confirm_yes_selected {
- self.action_sender.send(Action::ConfirmDownloadEpisode).ok();
- } else {
- self.state.show_episode_download_confirm = false;
+ }
+ KeyCode::Right | KeyCode::Char('l') | KeyCode::Char('L') => {
+ if self.state.show_season_download_confirm {
+ self.state.season_download_confirm_yes_selected = false;
+ } else if self.state.show_episode_download_confirm {
+ self.state.episode_download_confirm_yes_selected = false;
+ } else if !self.state.subtitle_popup && !self.state.player_picker_popup
+ {
+ self.action_sender.send(Action::TabPane).ok();
}
- } else if self.state.subtitle_popup
- || self.state.player_picker_popup
- || self.state.is_download_subtitle_popup
- {
- self.action_sender.send(Action::Submit).ok();
- } else {
- match self.state.details_pane {
- crate::tui::state::DetailsPane::Streams => {
- self.action_sender.send(Action::PlayStream).ok();
- }
- crate::tui::state::DetailsPane::Seasons => {
- self.trigger_episode_fetch();
+ }
+ KeyCode::Enter => {
+ if self.state.show_season_download_confirm {
+ if self.state.season_download_confirm_yes_selected {
+ self.action_sender.send(Action::ConfirmDownloadSeason).ok();
+ } else {
+ self.state.show_season_download_confirm = false;
}
- crate::tui::state::DetailsPane::Episodes => {
- self.trigger_episode_fetch();
+ } else if self.state.show_episode_download_confirm {
+ if self.state.episode_download_confirm_yes_selected {
+ self.action_sender.send(Action::ConfirmDownloadEpisode).ok();
+ } else {
+ self.state.show_episode_download_confirm = false;
}
- crate::tui::state::DetailsPane::Languages => {
- let idx =
- self.state.language_list_state.selected().unwrap_or(0);
+ } else if self.state.subtitle_popup
+ || self.state.player_picker_popup
+ || self.state.is_download_subtitle_popup
+ {
+ self.action_sender.send(Action::Submit).ok();
+ } else {
+ match self.state.details_pane {
+ crate::tui::state::DetailsPane::Streams => {
+ self.action_sender.send(Action::PlayStream).ok();
+ }
+ crate::tui::state::DetailsPane::Seasons => {
+ self.trigger_episode_fetch();
+ }
+ crate::tui::state::DetailsPane::Episodes => {
+ self.trigger_episode_fetch();
+ }
+ crate::tui::state::DetailsPane::Languages => {
+ let idx =
+ self.state.language_list_state.selected().unwrap_or(0);
- self.action_sender.send(Action::SelectLanguage(idx)).ok();
+ self.action_sender.send(Action::SelectLanguage(idx)).ok();
+ }
}
}
}
- }
- _ => {}
- },
- },
+ _ => {}
+ },
+ }
+ }
}
None
}
@@ -1295,6 +1377,47 @@ mod tests {
assert_eq!(app.state.search_list_state.selected(), Some(0));
}
+ #[tokio::test]
+ async fn test_delete_history_item_with_key() {
+ let mut app = App::new();
+ app.state.active_screen = crate::tui::state::Screen::Home;
+ app.state.input_mode = InputMode::Normal;
+ app.state.search_query.set_content("/history");
+
+ let item = crate::history::WatchHistoryItem {
+ provider: "moviebox".to_string(),
+ subject_id: "hist-1".to_string(),
+ title: "History Movie".to_string(),
+ cover_url: None,
+ stype: 1,
+ release_year: "2024".to_string(),
+ season: 0,
+ episode: 0,
+ progress_seconds: 50,
+ duration_seconds: Some(500),
+ completed: false,
+ timestamp: 1000,
+ };
+ app.state.history.record_start(&item, 50);
+ app.state.search_results.push(item.to_search_result());
+ app.state.search_list_state.select(Some(0));
+ assert_eq!(app.state.search_results.len(), 1);
+ assert_eq!(app.state.history.recent.len(), 1);
+
+ app.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::empty()))
+ .await;
+
+ assert!(app.state.search_results.is_empty());
+ assert!(app.state.history.recent.is_empty());
+ let notif = app
+ .state
+ .notifications
+ .back()
+ .expect("notification emitted");
+ assert_eq!(notif.title, "History");
+ assert_eq!(notif.message, "Removed: History Movie");
+ }
+
#[tokio::test]
async fn test_update_modal_keystroke_isolation() {
let mut app = App::new();
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 3d2412b..3189a92 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -71,7 +71,7 @@ impl App {
.collect::<Vec<_>>();
let confirm_label = "Select";
match click_in_picker(
- crate::tui::overlay::picker_layout(area, &items, confirm_label, 20),
+ crate::tui::overlay::picker_layout(area, &items, confirm_label, 10),
col,
row,
&self.state.player_picker_state,
@@ -139,7 +139,7 @@ impl App {
})
.collect();
match click_in_picker(
- crate::tui::overlay::picker_layout(area, &items, "Apply", 24),
+ crate::tui::overlay::picker_layout(area, &items, "Apply", 16),
col,
row,
&self.state.theme_list_state,
@@ -294,7 +294,7 @@ impl App {
self.state.notify(
NotificationKind::Info,
"Homebrew Upgrade",
- "Run 'brew upgrade moviebox-tui' in your terminal to update.",
+ "Run: brew upgrade moviebox-tui",
);
} else {
self.action_sender.send(Action::StartSelfUpdate).ok();
@@ -325,7 +325,7 @@ impl App {
"Use"
};
match click_in_picker(
- crate::tui::overlay::picker_layout(area, &items, confirm_label, 32),
+ crate::tui::overlay::picker_layout(area, &items, confirm_label, 20),
col,
row,
&self.state.subtitle_list_state,
@@ -533,7 +533,7 @@ impl App {
if col >= inner_area.left()
&& col < inner_area.right()
&& row >= inner_area.top()
- && row < inner_area.bottom().saturating_sub(1)
+ && row < inner_area.bottom()
{
let clicked_idx = (row - inner_area.top()) as usize;
if let Some(&provider) = available.get(clicked_idx) {
@@ -759,23 +759,8 @@ impl App {
return None;
}
- let search_bar_area = {
- let chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(1),
- Constraint::Length(1),
- Constraint::Min(0),
- ])
- .split(area);
-
- Rect {
- x: chunks[0].x + 2,
- y: chunks[0].y,
- width: chunks[0].width.saturating_sub(4),
- height: chunks[0].height,
- }
- };
+ let (search_bar_area, results_chunk) =
+ crate::tui::screens::home::search_results_layout(area);
if self.state.input_mode == InputMode::Editing && !self.state.search_suggestions.is_empty()
{
@@ -834,18 +819,12 @@ impl App {
return None;
}
- let results_y = 2;
- if row >= results_y && row < area.height {
+ if row >= results_chunk.y && row < area.height {
if self.state.search_results.is_empty() {
let next_label = self.state.next_provider().label();
let ctrl_p = crate::tui::text::CTRL_P_STR;
let (btn1, btn2) = crate::tui::screens::home::no_results_button_hitboxes(
- Rect {
- x: area.x,
- y: results_y,
- width: area.width,
- height: area.height.saturating_sub(results_y),
- },
+ results_chunk,
next_label,
ctrl_p,
self.state.is_tv_mode,
@@ -872,16 +851,18 @@ impl App {
}
return None;
}
+ if col < results_chunk.x || col >= results_chunk.right() {
+ return None;
+ }
let metrics = self
.state
- .result_metrics(area.height.saturating_sub(results_y + 1), area.width);
+ .result_metrics(results_chunk.height.saturating_sub(1), results_chunk.width);
let row_height = metrics.row_height;
- let clicked_relative_row = row.saturating_sub(results_y);
+ let clicked_relative_row = row.saturating_sub(results_chunk.y);
let visual_row = (clicked_relative_row / row_height) as usize;
let col_step = (metrics.col_width + 1).max(1);
- let clicked_column = (((col.saturating_sub(area.x)) / col_step) as usize)
+ let clicked_column = (((col.saturating_sub(results_chunk.x)) / col_step) as usize)
.min(metrics.columns.saturating_sub(1) as usize);
-
let page_start = self.state.result_scroll;
let target_idx = page_start + visual_row * metrics.columns as usize + clicked_column;
@@ -1400,16 +1381,12 @@ mod tests {
app.state.search_results = vec![];
let area = Rect::new(0, 0, 100, 30);
- let results_y = 2;
+ let (_search_bar_area, results_chunk) =
+ crate::tui::screens::home::search_results_layout(area);
let next_label = app.state.next_provider().label();
let ctrl_p = crate::tui::text::CTRL_P_STR;
let (btn1, btn2) = crate::tui::screens::home::no_results_button_hitboxes(
- Rect {
- x: area.x,
- y: results_y,
- width: area.width,
- height: area.height.saturating_sub(results_y),
- },
+ results_chunk,
next_label,
ctrl_p,
app.state.is_tv_mode,
@@ -1425,6 +1402,7 @@ mod tests {
}
#[tokio::test]
async fn test_home_provider_pill_mouse_click_opens_popup() {
+ let original_config = crate::config::load();
let mut app = App::new();
app.state.active_screen = crate::tui::state::Screen::Home;
app.state.input_mode = crate::tui::state::InputMode::Normal;
@@ -1470,11 +1448,23 @@ mod tests {
assert!(!app.state.show_provider_popup);
assert_eq!(app.state.active_provider, ProviderKind::FourKHdHub);
+ app.handle_home_mouse(pill_rect.x + 1, pill_rect.y, area);
+ assert!(app.state.show_provider_popup);
+ let last_idx = available.len() - 1;
+ let last_provider = available[last_idx];
+ let last_target_y = inner.y + last_idx as u16;
+ app.handle_home_mouse(inner.x + 1, last_target_y, area);
+ assert!(!app.state.show_provider_popup);
+ assert_eq!(app.state.active_provider, last_provider);
+
+ let pill_rect =
+ crate::tui::screens::home::search_bar_provider_pill_rect(search_card_area, &app.state);
app.handle_home_mouse(pill_rect.x + 1, pill_rect.y, area);
assert!(app.state.show_provider_popup);
app.handle_home_mouse(area.x, area.y, area);
assert!(!app.state.show_provider_popup);
- assert_eq!(app.state.active_provider, ProviderKind::FourKHdHub);
+ assert_eq!(app.state.active_provider, last_provider);
+ crate::config::save(&original_config);
}
#[tokio::test]
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index a679f38..a4da87a 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -372,6 +372,10 @@ impl App {
self.state.provider_list_state.select(None);
return None;
}
+ if !self.state.notifications.is_empty() {
+ self.state.notifications.clear();
+ return None;
+ }
if self.state.favorites_focus {
self.state.favorites_focus = false;
self.state.favorites_landing_state.select(None);
@@ -969,4 +973,15 @@ mod tests {
assert_eq!(notif.kind, NotificationKind::Info);
assert_eq!(notif.title, "Playback Cancelled");
}
+
+ #[tokio::test]
+ async fn test_escape_dismisses_active_notifications() {
+ let mut app = App::new();
+ app.state
+ .notify(NotificationKind::Info, "Test Notification", "Some message");
+ assert_eq!(app.state.notifications.len(), 1);
+
+ app.handle_action(Action::GoBack).await;
+ assert!(app.state.notifications.is_empty());
+ }
}
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index b6e8224..4607828 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -88,7 +88,6 @@ impl App {
} => {
self.state.is_resolving_playback = false;
self.state.pending_playback_source = None;
- let provider_name = source.provider.label();
let chosen_name = chosen.label();
let body = if !compatible_alternatives.is_empty() {
let alternatives_str = compatible_alternatives
@@ -96,29 +95,16 @@ impl App {
.map(|k| k.label())
.collect::<Vec<_>>()
.join(" or ");
- if source.provider == ProviderKind::FourKHdHub {
- format!(
- "{} cannot play this {} stream due to required authentication headers. Set {} as default in /settings.",
- chosen_name, provider_name, alternatives_str
- )
- } else {
- format!(
- "{} cannot play this {} stream due to required authentication headers. Set {} as default in /settings, or press Ctrl+P for 4KHDHub.",
- chosen_name, provider_name, alternatives_str
- )
- }
+ format!(
+ "{chosen_name} lacks header support. Switch to {alternatives_str} in /settings."
+ )
} else {
- if source.provider == ProviderKind::FourKHdHub {
- format!(
- "{} cannot play this {} stream due to required authentication headers. Install a compatible player (mpv).",
- chosen_name, provider_name
- )
- } else {
- format!(
- "{} cannot play this {} stream due to required authentication headers. Install a compatible player (mpv) or press Ctrl+P for 4KHDHub.",
- chosen_name, provider_name
- )
- }
+ let supported_str = crate::player::header_capable_players()
+ .iter()
+ .map(|k| k.label())
+ .collect::<Vec<_>>()
+ .join(" or ");
+ format!("{chosen_name} lacks header support. Install {supported_str}.")
};
self.state.notify(
NotificationKind::Warning,
@@ -126,26 +112,18 @@ impl App {
body,
);
}
- PlaybackResolution::NoCompatiblePlayer { available } => {
+ PlaybackResolution::NoCompatiblePlayer { available: _ } => {
self.state.is_resolving_playback = false;
self.state.pending_playback_source = None;
- let players_str = available
+ let supported_str = crate::player::header_capable_players()
.iter()
.map(|k| k.label())
.collect::<Vec<_>>()
- .join(", ");
- let provider_name = source.provider.label();
- let action_hint = if source.provider == ProviderKind::FourKHdHub {
- "Install mpv."
- } else {
- "Install mpv or press Ctrl+P for 4KHDHub."
- };
+ .join(" or ");
self.state.notify(
NotificationKind::Error,
"Incompatible Media Player",
- format!(
- "None of your detected players ({players_str}) support authentication headers required by {provider_name} streams. {action_hint}"
- ),
+ format!("Headers unsupported. Install {supported_str}."),
);
}
PlaybackResolution::NoPlayersInstalled => {
@@ -511,11 +489,7 @@ impl App {
self.state.notify(
NotificationKind::Info,
"Preparing playback",
- format!(
- "Resolving {} from {}...",
- first_mirror.label,
- release.provider.label()
- ),
+ format!("Resolving {}...", first_mirror.label),
);
let direct_source = crate::providers::models::PlaybackSource {
provider: release.provider,
@@ -595,12 +569,7 @@ impl App {
subtitle: None,
source_label: first_mirror.label.clone(),
};
- let subject_id = self
- .state
- .selected_details
- .as_ref()
- .map(|d| d.id.value.clone())
- .unwrap_or_default();
+ let subject_id = self.state.active_subject_id.clone().unwrap_or_default();
let resource_id = self.get_selected_resource_id();
if let Some(rid) = resource_id {
@@ -626,6 +595,8 @@ impl App {
ids
})
.unwrap_or_default();
+ let season = self.state.selected_season;
+ let episode = self.state.selected_episode;
tokio::spawn(async move {
let cached = tokio::task::spawn_blocking({
let subject_id = subject_id.clone();
@@ -643,7 +614,13 @@ impl App {
}
let result = tokio::time::timeout(
std::time::Duration::from_secs(15),
- service.get_ext_captions(&subject_id, &rid, &sibling_ids),
+ service.get_ext_captions(
+ &subject_id,
+ &rid,
+ &sibling_ids,
+ season,
+ episode,
+ ),
)
.await;
match result {
@@ -781,11 +758,7 @@ impl App {
self.state.notify(
NotificationKind::Error,
format!("{} Incompatible", kind.label()),
- format!(
- "{} cannot play this {} stream because it requires authentication headers.",
- kind.label(),
- source.provider.label(),
- ),
+ format!("{} lacks stream header support.", kind.label()),
);
return None;
}
@@ -1010,16 +983,15 @@ mod tests {
assert!(content.contains("Subtitles"));
assert!(content.contains("No subtitles"));
assert!(content.contains("English"));
- assert!(content.contains("Use"));
-
let items = vec!["No subtitles".to_string(), "English".to_string()];
let popup_layout = crate::tui::overlay::picker_layout(
ratatui::layout::Rect::new(0, 0, 80, 24),
&items,
"Use",
- 32,
+ 20,
);
- assert_eq!(popup_layout.height, 6);
+ assert_eq!(popup_layout.height, 4);
+ assert_eq!(popup_layout.width, 20);
}
#[tokio::test]
@@ -1078,11 +1050,7 @@ mod tests {
let notification = app.state.notifications.back().expect("notification posted");
assert_eq!(notification.title, "VLC Incompatible");
- assert!(
- notification
- .message
- .contains("VLC cannot play this MovieBox stream")
- );
+ assert!(notification.message.contains("VLC lacks header support"));
assert!(notification.message.contains("mpv"));
}
#[tokio::test]
@@ -1176,4 +1144,60 @@ mod tests {
.contains("pkg install -y termux-tools termux-am")
);
}
+
+ #[tokio::test]
+ async fn test_playback_captures_active_subject_and_episode() {
+ let mut app = crate::tui::app::App::new();
+ app.state.active_screen = crate::tui::state::Screen::Details;
+ app.state.selected_season = 2;
+ app.state.selected_episode = 5;
+ app.state.active_subject_id = Some("dub_subject_42".to_string());
+ app.state.selected_details = Some(crate::providers::models::MediaDetails {
+ id: crate::providers::models::ProviderMediaId {
+ provider: crate::providers::models::ProviderKind::MovieBox,
+ value: "root_subject_100".to_string(),
+ },
+ title: "Test Series".to_string(),
+ media_type: crate::models::MediaType::Series,
+ year: None,
+ description: None,
+ tagline: None,
+ imdb_rating: None,
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: None,
+ genres: Vec::new(),
+ seasons: Vec::new(),
+ dubs: Vec::new(),
+ });
+ let mirror = crate::providers::models::SourceMirror {
+ label: "1080p".to_string(),
+ resolver_url: "https://example.com/video.mp4".to_string(),
+ headers: Vec::new(),
+ direct_file: true,
+ };
+ app.state.selected_resources = vec![crate::providers::models::Release {
+ provider: crate::providers::models::ProviderKind::MovieBox,
+ filename: "Test S02E05 1080p".to_string(),
+ quality: Some("1080p".to_string()),
+ codec: None,
+ language: None,
+ size_bytes: None,
+ season: Some(2),
+ episode: Some(5),
+ mirrors: vec![mirror],
+ resource_id: Some("res_s2e5".to_string()),
+ }];
+ app.state.resource_list_state.select(Some(0));
+ assert_eq!(
+ app.state.active_subject_id.as_deref(),
+ Some("dub_subject_42")
+ );
+ assert_eq!(app.get_selected_resource_id().as_deref(), Some("res_s2e5"));
+ assert_eq!(app.state.selected_season, 2);
+ assert_eq!(app.state.selected_episode, 5);
+ }
}
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index fde8e63..35a6260 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -1556,7 +1556,7 @@ impl App {
}
match tokio::time::timeout(
std::time::Duration::from_secs(15),
- client.fetch_resource_page(&id_clone, 0, page),
+ client.fetch_resource_page(&id_clone, 0, 0, 0, page),
)
.await
{
@@ -1613,7 +1613,7 @@ impl App {
}
match tokio::time::timeout(
std::time::Duration::from_secs(15),
- c.fetch_resource_page(&id, res, page),
+ c.fetch_resource_page(&id, 0, 0, res, page),
)
.await
{
@@ -1842,6 +1842,8 @@ impl App {
ids
})
.unwrap_or_default();
+ let season = self.state.selected_season;
+ let episode = self.state.selected_episode;
tokio::spawn(async move {
let already_cached = tokio::task::spawn_blocking({
let subject_id = subject_id.clone();
@@ -1856,7 +1858,13 @@ impl App {
if !already_cached {
if let Ok(res) = service
- .get_ext_captions(&subject_id, &rid, &sibling_ids)
+ .get_ext_captions(
+ &subject_id,
+ &rid,
+ &sibling_ids,
+ season,
+ episode,
+ )
.await
{
tokio::task::spawn_blocking(move || {
@@ -1895,10 +1903,18 @@ impl App {
ids
})
.unwrap_or_default();
+ let season = self.state.selected_season;
+ let episode = self.state.selected_episode;
tokio::spawn(async move {
if let Ok(res) = service
- .get_ext_captions(&subject_id, &rid, &sibling_ids)
+ .get_ext_captions(
+ &subject_id,
+ &rid,
+ &sibling_ids,
+ season,
+ episode,
+ )
.await
{
if pref.is_none() {
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index 15df485..1e0ba37 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -1068,13 +1068,9 @@ impl App {
&items,
&mut self.state.subtitle_list_state,
crate::tui::overlay::PickerSpec {
- title: if self.state.is_download_subtitle_popup {
- "Download Subtitles"
- } else {
- "Subtitles"
- },
+ title: "Subtitles",
confirm_label,
- minimum_width: 32,
+ minimum_width: 20,
show_counter: true,
},
&self.theme,
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 635d560..e85bda3 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -546,27 +546,45 @@ impl App {
self.state.notify(
NotificationKind::Info,
"Clearing Cache",
- "Clearing temporary disk cache files...",
+ "Clearing temporary disk cache...",
);
self.action_sender.send(Action::ClearCache).ok();
}
1 => {
+ self.state.history.clear();
+ self.state.homepage_cache.clear();
+ if self
+ .state
+ .search_query
+ .trim()
+ .eq_ignore_ascii_case("/history")
+ {
+ self.state.search_results.clear();
+ self.state.search_list_state.select(None);
+ }
+ self.state.notify(
+ NotificationKind::Success,
+ "History",
+ "Watch history cleared",
+ );
+ }
+ 2 => {
self.state.manual_update_check = true;
self.state.notify(
NotificationKind::Info,
"Checking for updates",
- "Querying GitHub for latest releases...",
+ "Checking GitHub releases...",
);
self.action_sender.send(Action::CheckForUpdates).ok();
}
- 2 => {
+ 3 => {
const REPO_URL: &str = "https://github.com/mesamirh/MovieBox-Tui";
match open::that(REPO_URL) {
Ok(()) => {
self.state.notify(
NotificationKind::Info,
"GitHub",
- "Opening repository in default web browser...",
+ "Opening repository in browser...",
);
}
Err(error) => {
@@ -579,13 +597,13 @@ impl App {
}
}
}
- 3 => {
+ 4 => {
self.state.bdix_probed = false;
self.action_sender.send(Action::CheckBdixNetwork).ok();
self.state.notify(
NotificationKind::Info,
"BDIX Check",
- "Probing BDIX mirrors on local network...",
+ "Probing local network mirrors...",
);
}
_ => {}
diff --git a/src/tui/commands.rs b/src/tui/commands.rs
index c40daec..e1d339b 100644
--- a/src/tui/commands.rs
+++ b/src/tui/commands.rs
@@ -24,15 +24,6 @@ impl SlashCommand {
Self::Exit,
];
- pub const PRIMARY: [Self; 6] = [
- Self::Settings,
- Self::Browse,
- Self::History,
- Self::Favorites,
- Self::Clear,
- Self::Help,
- ];
-
pub fn name(self) -> &'static str {
match self {
Self::Settings => "/settings",
@@ -216,7 +207,6 @@ mod tests {
fn test_core_commands_and_aliases_parse() {
let state = AppState::default();
assert_eq!(SlashCommand::ALL.len(), 8);
- assert_eq!(SlashCommand::PRIMARY.len(), 6);
assert_eq!(SlashCommand::parse("/exit"), Some(SlashCommand::Exit));
assert_eq!(SlashCommand::parse("/quit"), Some(SlashCommand::Exit));
assert_eq!(SlashCommand::parse("/q"), Some(SlashCommand::Exit));
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index 92fae7f..ef95487 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -35,7 +35,7 @@ pub fn picker_layout(
.map(|item| crate::tui::text::width(item))
.max()
.unwrap_or(0)
- .saturating_add(2);
+ .saturating_add(6);
centered(
area,
content_width as u16,
@@ -94,6 +94,21 @@ pub fn settings_modal_layout(area: Rect, category: crate::tui::state::SettingsCa
Rect::new(x, y, width, popup_height)
}
+pub fn help_modal_layout(area: Rect, desired_width: u16, desired_height: 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.clamp(46, 120).min(available_width);
+ let height = desired_height.min(available_height).max(1);
+ let x = area.x + area.width.saturating_sub(width) / 2;
+ let search_y = if area.height >= 24 {
+ area.y + 2 + 6 + 1 + 2
+ } else {
+ area.y + 1 + 2 + 1 + 1
+ };
+ let y = search_y.min(area.bottom().saturating_sub(height));
+ Rect::new(x, y, width, height)
+}
+
pub fn download_confirm_layout(
area: Rect,
summary_lines: usize,
@@ -124,7 +139,13 @@ pub fn picker(
) {
let lines: Vec<Line<'static>> = items
.iter()
- .map(|item| Line::from(vec![Span::raw(item.clone())]))
+ .map(|item| {
+ Line::from(vec![
+ Span::raw(" "),
+ Span::raw(item.clone()),
+ Span::raw(" "),
+ ])
+ })
.collect();
picker_with_lines(
frame,
@@ -247,14 +268,13 @@ pub fn confirmation(
Paragraph::new(summary.to_vec()).alignment(Alignment::Center),
sections[0],
);
- use ratatui::style::Color;
let confirm_btn_style = if confirm_selected {
if basic_terminal {
theme.text.add_modifier(Modifier::REVERSED | Modifier::BOLD)
} else {
Style::default()
- .bg(theme.accent.fg.unwrap_or(Color::Cyan))
- .fg(theme.crust.fg.unwrap_or(Color::Black))
+ .bg(theme.accent.fg.unwrap_or(theme.base))
+ .fg(theme.crust_color())
.add_modifier(Modifier::BOLD)
}
} else {
@@ -266,8 +286,8 @@ pub fn confirmation(
theme.text.add_modifier(Modifier::REVERSED | Modifier::BOLD)
} else {
Style::default()
- .bg(theme.surface1.fg.unwrap_or(Color::DarkGray))
- .fg(theme.text.fg.unwrap_or(Color::White))
+ .bg(theme.surface1_color())
+ .fg(theme.text.fg.unwrap_or(theme.base))
.add_modifier(Modifier::BOLD)
}
} else {
@@ -293,12 +313,19 @@ pub fn notifications(
let bottom_offset = if download_active { 5 } else { 2 };
let mut y = area.bottom().saturating_sub(bottom_offset);
- for notification in notifications.iter().rev().take(3) {
+ let (max_visible, max_card_w, max_msg_lines) = if area.height < 20 || area.width < 65 {
+ (1, 42.min(area.width.saturating_sub(4) as usize), 1)
+ } else if area.height < 30 {
+ (2, 56.min(area.width.saturating_sub(4) as usize), 2)
+ } else {
+ (3, 64.min(area.width.saturating_sub(4) as usize), 3)
+ };
+
+ for notification in notifications.iter().rev().take(max_visible) {
let (badge, badge_style) = notification_style(notification.kind, theme, basic_terminal);
let has_message =
!notification.message.is_empty() && notification.message != notification.title;
- let max_card_width = (area.width.saturating_sub(4) as usize).min(72);
let title_w = crate::tui::text::width(&notification.title).saturating_add(6);
let badge_w = badge.len().saturating_add(6);
let raw_msg_w = if has_message {
@@ -310,14 +337,14 @@ pub fn notifications(
let target_card_width = title_w
.max(badge_w)
.max(raw_msg_w)
- .clamp(20, max_card_width.max(20)) as u16;
+ .clamp(20, max_card_w.max(20)) as u16;
let inner_width = (target_card_width.saturating_sub(4) as usize).max(1);
let msg_lines: Vec<String> = if has_message {
crate::tui::text::wrap_text(&notification.message, inner_width)
.into_iter()
- .take(4)
+ .take(max_msg_lines)
.collect()
} else {
Vec::new()
@@ -328,7 +355,6 @@ pub fn notifications(
if target_card_width < 10 || y < area.y.saturating_add(height) {
break;
}
-
y = y.saturating_sub(height);
let toast_area = Rect::new(
@@ -461,7 +487,7 @@ pub(crate) fn selection_style(theme: &Theme, basic_terminal: bool) -> Style {
.fg(theme.highlight.fg.unwrap_or(theme.base))
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
} else {
- let bg = theme.surface1.fg.unwrap_or(theme.base);
+ let bg = theme.surface1_color();
let fg = theme
.highlight
.fg
@@ -518,12 +544,19 @@ pub fn notification_rects(
let mut y = area.bottom().saturating_sub(bottom_offset);
let theme_placeholder = Theme::default();
- for (rev_idx, notification) in notifications.iter().rev().take(3).enumerate() {
+ let (max_visible, max_card_w, max_msg_lines) = if area.height < 20 || area.width < 65 {
+ (1, 42.min(area.width.saturating_sub(4) as usize), 1)
+ } else if area.height < 30 {
+ (2, 56.min(area.width.saturating_sub(4) as usize), 2)
+ } else {
+ (3, 64.min(area.width.saturating_sub(4) as usize), 3)
+ };
+
+ for (rev_idx, notification) in notifications.iter().rev().take(max_visible).enumerate() {
let (badge, _) = notification_style(notification.kind, &theme_placeholder, basic_terminal);
let has_message =
!notification.message.is_empty() && notification.message != notification.title;
- let max_card_width = (area.width.saturating_sub(4) as usize).min(72);
let title_w = crate::tui::text::width(&notification.title).saturating_add(6);
let badge_w = badge.len().saturating_add(6);
let raw_msg_w = if has_message {
@@ -535,14 +568,14 @@ pub fn notification_rects(
let target_card_width = title_w
.max(badge_w)
.max(raw_msg_w)
- .clamp(20, max_card_width.max(20)) as u16;
+ .clamp(20, max_card_w.max(20)) as u16;
let inner_width = (target_card_width.saturating_sub(4) as usize).max(1);
let msg_lines: Vec<String> = if has_message {
crate::tui::text::wrap_text(&notification.message, inner_width)
.into_iter()
- .take(4)
+ .take(max_msg_lines)
.collect()
} else {
Vec::new()
@@ -856,4 +889,24 @@ mod tests {
let (_, error_style) = notification_style(NotificationKind::Error, &theme, false);
assert_eq!(error_style.fg, theme.error.fg);
}
+
+ #[test]
+ fn test_notification_rects_adaptive_tiering() {
+ let mut queue = std::collections::VecDeque::new();
+ queue.push_back(Notification::new(NotificationKind::Info, "N1", "M1"));
+ queue.push_back(Notification::new(NotificationKind::Info, "N2", "M2"));
+ queue.push_back(Notification::new(NotificationKind::Info, "N3", "M3"));
+
+ let compact_area = Rect::new(0, 0, 60, 18);
+ let compact_rects = notification_rects(compact_area, &queue, false, false);
+ assert_eq!(compact_rects.len(), 1);
+
+ let standard_area = Rect::new(0, 0, 80, 24);
+ let standard_rects = notification_rects(standard_area, &queue, false, false);
+ assert_eq!(standard_rects.len(), 2);
+
+ let large_area = Rect::new(0, 0, 120, 35);
+ let large_rects = notification_rects(large_area, &queue, false, false);
+ assert_eq!(large_rects.len(), 3);
+ }
}
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index 9982881..d05d3db 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -10,9 +10,9 @@ use crate::tui::{
use ratatui::{
Frame,
layout::{Alignment, Constraint, Direction, Layout, Rect},
- style::{Color, Modifier, Style},
+ style::{Modifier, Style},
text::{Line, Span},
- widgets::{Block, Borders, List, ListItem, Paragraph, Wrap},
+ widgets::{Block, Borders, Paragraph, Wrap},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -325,6 +325,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
})
.unwrap_or("N/A");
let is_series = details.is_series() && !state.available_seasons.is_empty();
+ let has_languages = details.has_languages();
let type_str = if is_series { "Series" } else { "Movie" };
let genres = if !details.genres.is_empty() {
@@ -478,7 +479,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
}
- let bullet_sep = if state.basic_terminal { " - " } else { " · " };
+ let bullet_sep = if state.basic_terminal { " - " } else { " " };
let (b_year_s, b_sep_s, b_type_s, b_dur_s, b_rating_s, b_audio_lbl_s, b_audio_val_s, b_prov_s) =
if modal_active {
(
@@ -503,11 +504,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
theme.subtext1,
)
};
- let mut badge_spans = vec![
- Span::styled(year, b_year_s),
- Span::styled(bullet_sep, b_sep_s),
- Span::styled(type_str, b_type_s),
- ];
+ let mut badge_spans = vec![Span::styled(type_str, b_type_s)];
+ if !year.is_empty() && year != "N/A" {
+ badge_spans.insert(0, Span::styled(bullet_sep, b_sep_s));
+ badge_spans.insert(0, Span::styled(year, b_year_s));
+ }
if !duration.trim().is_empty() && duration != "N/A" {
badge_spans.push(Span::styled(bullet_sep, b_sep_s));
@@ -524,16 +525,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
badge_spans.push(Span::styled(imdb_rating, b_rating_s));
}
- let audio_str = if details.has_languages() {
- let count = details.dubs.len();
- if count > 1 {
- Some(format!("{count} Tracks"))
- } else {
- details
- .dubs
- .first()
- .map(|d| clean_language_name(&d.language))
- }
+ let audio_str = if has_languages {
+ None
} else {
details
.audios
@@ -597,7 +590,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
theme.subtext1.add_modifier(Modifier::BOLD),
Style::default().fg(theme_color(
theme.subtext1,
- theme.text.fg.unwrap_or(Color::White),
+ theme.text.fg.unwrap_or(theme.base),
)),
theme.overlay1,
)
@@ -730,7 +723,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let meta_p = Paragraph::new(final_lines);
frame.render_widget(meta_p, meta_area);
- let has_languages = details.has_languages();
let streams_count = state.selected_resources.len();
render_workflow(
@@ -765,14 +757,29 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.get(state.season_list_state.selected().unwrap_or(0))
.map_or(0, Vec::len);
let language_count = details.dubs.len();
- language_count
- .max(state.available_seasons.len())
- .max(episode_count)
- .min((bottom_area.height / 3).clamp(4, 10) as usize) as u16
- + 2
+ let max_visible_items = visible_selector_panes
+ .iter()
+ .map(|pane| match pane {
+ crate::tui::state::DetailsPane::Languages => language_count,
+ crate::tui::state::DetailsPane::Seasons => state.available_seasons.len(),
+ crate::tui::state::DetailsPane::Episodes => episode_count,
+ crate::tui::state::DetailsPane::Streams => 0,
+ })
+ .max()
+ .unwrap_or(0);
+ let max_rows = (bottom_area.height / 3).clamp(4, 10) as usize;
+ (max_visible_items.min(max_rows) as u16) + 2
+ };
+
+ let streams_height_cap = if state.has_streams_settled && streams_count > 0 {
+ let capped =
+ (streams_count as u16 + 3).min(bottom_area.height.saturating_sub(selector_height));
+ Constraint::Length(capped)
+ } else {
+ Constraint::Min(3)
};
- let lower_chunks = Layout::vertical([Constraint::Length(selector_height), Constraint::Min(3)])
+ let lower_chunks = Layout::vertical([Constraint::Length(selector_height), streams_height_cap])
.split(bottom_area);
let selector_area = lower_chunks[0];
let streams_area = lower_chunks[1];
@@ -806,11 +813,19 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if has_languages {
use ratatui::widgets::{List, ListItem};
+ let language_focused =
+ !modal_active && state.details_pane == crate::tui::state::DetailsPane::Languages;
+ let selected_lang = state.language_list_state.selected();
let mut lang_items = Vec::new();
- for dub in &details.dubs {
+ for (i, dub) in details.dubs.iter().enumerate() {
let name = clean_language_name(&dub.language);
+ let is_selected = Some(i) == selected_lang;
let item_style = if modal_active {
theme.muted
+ } else if is_selected && language_focused {
+ crate::tui::overlay::selection_style(theme, state.basic_terminal)
+ } else if is_selected {
+ theme.subtext1.add_modifier(Modifier::BOLD)
} else {
theme.text
};
@@ -818,30 +833,25 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
let language_count = lang_items.len();
- let language_focused =
- !modal_active && state.details_pane == crate::tui::state::DetailsPane::Languages;
- let (lang_border, lang_title_style, lang_highlight_style, lang_highlight_symbol) =
+ let (lang_border, lang_title_style, _lang_highlight_style, _lang_highlight_symbol) =
pane_styles(language_focused, modal_active, state.basic_terminal, theme);
- let lang_list = List::new(lang_items)
- .block(
- Block::default()
- .borders(Borders::ALL)
- .border_type(crate::tui::overlay::border_type(state.basic_terminal))
- .title(pane_title(
- "Audio",
- language_count,
- crate::tui::state::DetailsPane::Languages,
- language_focused,
- state,
- lang_area.map_or(0, |a| a.width),
- modal_active,
- ))
- .title_style(lang_title_style)
- .border_style(lang_border)
- .padding(ratatui::widgets::Padding::horizontal(1)),
- )
- .highlight_style(lang_highlight_style)
- .highlight_symbol(lang_highlight_symbol);
+ let lang_list = List::new(lang_items).block(
+ Block::default()
+ .borders(Borders::ALL)
+ .border_type(crate::tui::overlay::border_type(state.basic_terminal))
+ .title(pane_title(
+ "Audio",
+ language_count,
+ crate::tui::state::DetailsPane::Languages,
+ language_focused,
+ state,
+ lang_area.map_or(0, |a| a.width),
+ modal_active,
+ ))
+ .title_style(lang_title_style)
+ .border_style(lang_border)
+ .padding(ratatui::widgets::Padding::horizontal(1)),
+ );
if let Some(area) = lang_area {
frame.render_stateful_widget(lang_list, area, &mut state.language_list_state);
@@ -858,47 +868,50 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if is_series {
use ratatui::widgets::{List, ListItem};
+ let seasons_focused =
+ !modal_active && state.details_pane == crate::tui::state::DetailsPane::Seasons;
+ let selected_season = state.season_list_state.selected();
let seasons_items: Vec<ListItem> = state
.available_seasons
.iter()
- .map(|s| {
+ .enumerate()
+ .map(|(i, s)| {
+ let is_selected = Some(i) == selected_season;
let item_style = if modal_active {
theme.muted
+ } else if is_selected && seasons_focused {
+ crate::tui::overlay::selection_style(theme, state.basic_terminal)
+ } else if is_selected {
+ theme.subtext1.add_modifier(Modifier::BOLD)
} else {
theme.text
};
ListItem::new(format!("Season {}", s.number)).style(item_style)
})
.collect();
-
- let seasons_focused =
- !modal_active && state.details_pane == crate::tui::state::DetailsPane::Seasons;
let (
seasons_border,
seasons_title_style,
- seasons_highlight_style,
- seasons_highlight_symbol,
+ _seasons_highlight_style,
+ _seasons_highlight_symbol,
) = pane_styles(seasons_focused, modal_active, state.basic_terminal, theme);
- let seasons_list = List::new(seasons_items)
- .block(
- Block::default()
- .borders(Borders::ALL)
- .border_type(crate::tui::overlay::border_type(state.basic_terminal))
- .title(pane_title(
- "Seasons",
- state.available_seasons.len(),
- crate::tui::state::DetailsPane::Seasons,
- seasons_focused,
- state,
- seasons_area.map_or(0, |a| a.width),
- modal_active,
- ))
- .title_style(seasons_title_style)
- .border_style(seasons_border)
- .padding(ratatui::widgets::Padding::horizontal(1)),
- )
- .highlight_style(seasons_highlight_style)
- .highlight_symbol(seasons_highlight_symbol);
+ let seasons_list = List::new(seasons_items).block(
+ Block::default()
+ .borders(Borders::ALL)
+ .border_type(crate::tui::overlay::border_type(state.basic_terminal))
+ .title(pane_title(
+ "Seasons",
+ state.available_seasons.len(),
+ crate::tui::state::DetailsPane::Seasons,
+ seasons_focused,
+ state,
+ seasons_area.map_or(0, |a| a.width),
+ modal_active,
+ ))
+ .title_style(seasons_title_style)
+ .border_style(seasons_border)
+ .padding(ratatui::widgets::Padding::horizontal(1)),
+ );
if let Some(area) = seasons_area {
frame.render_stateful_widget(seasons_list, area, &mut state.season_list_state);
@@ -912,6 +925,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
);
}
+ let episodes_focused =
+ !modal_active && state.details_pane == crate::tui::state::DetailsPane::Episodes;
+ let (eps_border, eps_title_style, _eps_highlight_style, _eps_highlight_symbol) =
+ pane_styles(episodes_focused, modal_active, state.basic_terminal, theme);
+ let selected_ep = state.episode_list_state.selected();
+
let ep_items: Vec<ListItem> = if let Some(ep_numbers) = state
.available_episode_numbers
.get(state.season_list_state.selected().unwrap_or(0))
@@ -931,7 +950,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let ep_max_w = eps_area.map_or(40, |a| a.width.saturating_sub(6)) as usize;
ep_numbers
.iter()
- .map(|&ep| {
+ .enumerate()
+ .map(|(i, &ep)| {
+ let is_selected = Some(i) == selected_ep;
let ep_title_opt = details
.seasons
.iter()
@@ -945,38 +966,65 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
&& !trim.eq_ignore_ascii_case(&format!("EP {ep}"))
});
let ep_base = if let Some(t) = ep_title_opt {
- let candidate = format!("EP {ep:02} · {t}");
+ let candidate = format!("Episode {ep:02} · {t}");
crate::tui::text::truncate_width(&candidate, ep_max_w).into_owned()
} else {
- format!("EP {ep:02}")
+ format!("Episode {ep:02}")
};
- if modal_active {
- ListItem::new(format!("{unwatched_sym}{ep_base}")).style(theme.muted)
+ let item_style = if modal_active {
+ theme.muted
+ } else if is_selected && episodes_focused {
+ crate::tui::overlay::selection_style(theme, state.basic_terminal)
+ } else if is_selected {
+ theme.subtext1.add_modifier(Modifier::BOLD)
} else if let Some(hist) =
state
.history
.get_item(provider, subject_id, se_num, ep, Some(&title))
{
if hist.completed {
- ListItem::new(format!("{check_sym}{ep_base}")).style(theme.text_dim)
+ theme.text_dim
} else if hist.is_in_progress() {
- let progress_info =
- match (hist.progress_percentage(), hist.formatted_remaining()) {
- (Some(p), Some(r)) => format!(" ({:.0}% · {r})", p),
- (Some(p), None) => format!(" ({:.0}%)", p),
- (None, Some(r)) => format!(" ({r})"),
- (None, None) => String::new(),
- };
- ListItem::new(format!("{play_sym}{ep_base}{progress_info}"))
- .style(theme.accent)
+ theme.accent
} else {
- ListItem::new(format!("{unwatched_sym}{ep_base}")).style(theme.text)
+ theme.text
}
} else if state.history.is_watched(provider, subject_id, se_num, ep) {
- ListItem::new(format!("{check_sym}{ep_base}")).style(theme.text_dim)
+ theme.text_dim
} else {
- ListItem::new(format!("{unwatched_sym}{ep_base}")).style(theme.text)
- }
+ theme.text
+ };
+ let sym = if let Some(hist) =
+ state
+ .history
+ .get_item(provider, subject_id, se_num, ep, Some(&title))
+ {
+ if hist.completed {
+ check_sym
+ } else if hist.is_in_progress() {
+ play_sym
+ } else {
+ unwatched_sym
+ }
+ } else if state.history.is_watched(provider, subject_id, se_num, ep) {
+ check_sym
+ } else {
+ unwatched_sym
+ };
+ let progress_info = state
+ .history
+ .get_item(provider, subject_id, se_num, ep, Some(&title))
+ .filter(|h| !h.completed && h.is_in_progress())
+ .map(
+ |h| match (h.progress_percentage(), h.formatted_remaining()) {
+ (Some(p), Some(r)) => format!(" ({:.0}% · {r})", p),
+ (Some(p), None) => format!(" ({:.0}%)", p),
+ (None, Some(r)) => format!(" ({r})"),
+ (None, None) => String::new(),
+ },
+ )
+ .unwrap_or_default();
+ ListItem::new(format!("{sym}{ep_base}{progress_info}")).style(item_style)
})
.collect()
} else {
@@ -984,31 +1032,23 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
};
let episode_count = ep_items.len();
- let episodes_focused =
- !modal_active && state.details_pane == crate::tui::state::DetailsPane::Episodes;
- let (eps_border, eps_title_style, eps_highlight_style, eps_highlight_symbol) =
- pane_styles(episodes_focused, modal_active, state.basic_terminal, theme);
- let eps_list = List::new(ep_items)
- .block(
- Block::default()
- .borders(Borders::ALL)
- .border_type(crate::tui::overlay::border_type(state.basic_terminal))
- .title(pane_title(
- "Episodes",
- episode_count,
- crate::tui::state::DetailsPane::Episodes,
- episodes_focused,
- state,
- eps_area.map_or(0, |a| a.width),
- modal_active,
- ))
- .title_style(eps_title_style)
- .border_style(eps_border)
- .padding(ratatui::widgets::Padding::horizontal(1)),
- )
- .highlight_style(eps_highlight_style)
- .highlight_symbol(eps_highlight_symbol);
-
+ let eps_list = List::new(ep_items).block(
+ Block::default()
+ .borders(Borders::ALL)
+ .border_type(crate::tui::overlay::border_type(state.basic_terminal))
+ .title(pane_title(
+ "Episodes",
+ episode_count,
+ crate::tui::state::DetailsPane::Episodes,
+ episodes_focused,
+ state,
+ eps_area.map_or(0, |a| a.width),
+ modal_active,
+ ))
+ .title_style(eps_title_style)
+ .border_style(eps_border)
+ .padding(ratatui::widgets::Padding::horizontal(1)),
+ );
if let Some(area) = eps_area {
frame.render_stateful_widget(eps_list, area, &mut state.episode_list_state);
let episode_count = state
@@ -1081,7 +1121,79 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if !list.is_empty() {
let selected_idx = state.resource_list_state.selected();
- let list_items: Vec<ListItem> = list
+ use ratatui::widgets::{Cell, Row, Table};
+
+ let is_ultra_compact = streams_area.width < 58;
+ let is_compact = streams_area.width < 85;
+ let is_wide = streams_area.width >= 115;
+
+ let header_style = if modal_active {
+ theme.muted
+ } else {
+ theme.subtext1.add_modifier(Modifier::BOLD)
+ };
+
+ let (header_cells, widths): (Vec<Cell<'static>>, Vec<Constraint>) = if is_ultra_compact {
+ (
+ vec![Cell::from("RES"), Cell::from("SIZE"), Cell::from("RELEASE")],
+ vec![
+ Constraint::Length(8),
+ Constraint::Length(8),
+ Constraint::Min(15),
+ ],
+ )
+ } else if is_compact {
+ (
+ vec![
+ Cell::from("RES"),
+ Cell::from("SIZE"),
+ Cell::from("CODEC"),
+ Cell::from("RELEASE"),
+ ],
+ vec![
+ Constraint::Length(8),
+ Constraint::Length(8),
+ Constraint::Length(8),
+ Constraint::Min(20),
+ ],
+ )
+ } else if is_wide {
+ (
+ vec![
+ Cell::from("RES"),
+ Cell::from("SIZE"),
+ Cell::from("MEDIA TAGS"),
+ Cell::from("SOURCE"),
+ Cell::from("RELEASE"),
+ ],
+ vec![
+ Constraint::Length(8),
+ Constraint::Length(9),
+ Constraint::Length(18),
+ Constraint::Length(16),
+ Constraint::Min(24),
+ ],
+ )
+ } else {
+ (
+ vec![
+ Cell::from("RES"),
+ Cell::from("SIZE"),
+ Cell::from("MEDIA TAGS"),
+ Cell::from("RELEASE"),
+ ],
+ vec![
+ Constraint::Length(8),
+ Constraint::Length(9),
+ Constraint::Length(18),
+ Constraint::Min(20),
+ ],
+ )
+ };
+
+ let header = Row::new(header_cells).style(header_style).bottom_margin(0);
+
+ let table_rows: Vec<Row> = list
.iter()
.enumerate()
.map(|(i, file)| {
@@ -1120,7 +1232,32 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let release_title = clean_stream_release_title(&file.filename);
let clean_source = crate::tui::text::clean_stream_text(file.source_label());
- let upload_by = if !clean_source.is_empty() && clean_source != "Direct" {
+ let is_redundant_source = {
+ let l = clean_source.to_ascii_lowercase();
+ let parts: Vec<&str> = l
+ .split(|c: char| c == '-' || c.is_whitespace())
+ .filter(|p| !p.is_empty())
+ .collect();
+ !parts.is_empty()
+ && parts.iter().all(|p| {
+ matches!(
+ *p,
+ "multi"
+ | "res"
+ | "hevc"
+ | "h264"
+ | "x265"
+ | "x264"
+ | "1080p"
+ | "720p"
+ | "480p"
+ | "360p"
+ | "4k"
+ | "direct"
+ )
+ })
+ };
+ let upload_by = if !clean_source.is_empty() && !is_redundant_source {
clean_source
} else {
match file.provider {
@@ -1137,24 +1274,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
crate::providers::models::ProviderKind::Addons => "Addon".to_string(),
}
};
- let is_ultra_compact = streams_area.width < 58;
- let is_compact = streams_area.width < 85;
- let is_wide = streams_area.width >= 115;
- let stream_width = streams_area.width.saturating_sub(6) as usize;
-
- let mut stream_spans = Vec::new();
- stream_spans.extend(resolution_badge_spans(
+ let res_badge = resolution_badge_spans(
resolution,
theme,
state.basic_terminal,
modal_active,
- ));
-
- stream_spans.push(Span::styled(
- format!("{size_formatted:>7} "),
- primary_style,
- ));
+ is_selected && streams_focused,
+ );
let codec_str = codec.to_uppercase();
let tags = extract_media_tags(&file.filename, &codec_str);
@@ -1175,88 +1302,53 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
let sep = if state.basic_terminal { " - " } else { " · " };
let tags_or_codec = tag_parts.join(sep);
+ let tags_col = if tags_or_codec.is_empty() {
+ "-".to_string()
+ } else {
+ tags_or_codec
+ };
- if is_ultra_compact {
- stream_spans.push(Span::styled(
- crate::tui::text::truncate_width(&release_title, stream_width).into_owned(),
- primary_style,
- ));
+ let cells: Vec<Cell> = if is_ultra_compact {
+ vec![
+ Cell::from(ratatui::text::Line::from(res_badge)),
+ Cell::from(Span::styled(size_formatted.clone(), primary_style)),
+ Cell::from(Span::styled(release_title, primary_style)),
+ ]
} else if is_compact {
- stream_spans.push(Span::styled(format!("{codec:<6} "), secondary_style));
- stream_spans.push(Span::styled(
- crate::tui::text::truncate_width(&release_title, stream_width).into_owned(),
- primary_style,
- ));
+ vec![
+ Cell::from(ratatui::text::Line::from(res_badge)),
+ Cell::from(Span::styled(size_formatted.clone(), primary_style)),
+ Cell::from(Span::styled(format!("{codec:<6}"), secondary_style)),
+ Cell::from(Span::styled(release_title, primary_style)),
+ ]
} else if is_wide {
- let tags_col = if tags_or_codec.is_empty() {
- "-".to_string()
- } else {
- tags_or_codec
- };
- stream_spans.push(Span::styled(
- format!("{:<20} ", crate::tui::text::truncate_width(&tags_col, 20)),
- secondary_style,
- ));
- stream_spans.push(Span::styled(
- format!("{:<14} ", crate::tui::text::truncate_width(&upload_by, 14)),
- secondary_style,
- ));
- stream_spans.push(Span::styled(
- crate::tui::text::truncate_width(&release_title, stream_width).into_owned(),
- primary_style,
- ));
+ vec![
+ Cell::from(ratatui::text::Line::from(res_badge)),
+ Cell::from(Span::styled(size_formatted.clone(), primary_style)),
+ Cell::from(Span::styled(tags_col, secondary_style)),
+ Cell::from(Span::styled(upload_by, secondary_style)),
+ Cell::from(Span::styled(release_title, primary_style)),
+ ]
} else {
- let tags_col = if tags_or_codec.is_empty() {
- "-".to_string()
- } else {
- tags_or_codec
- };
- stream_spans.push(Span::styled(
- format!("{:<20} ", crate::tui::text::truncate_width(&tags_col, 20)),
- secondary_style,
- ));
- stream_spans.push(Span::styled(
- crate::tui::text::truncate_width(&release_title, stream_width).into_owned(),
- primary_style,
- ));
- }
- ListItem::new(ratatui::text::Line::from(stream_spans)).style(row_style)
+ vec![
+ Cell::from(ratatui::text::Line::from(res_badge)),
+ Cell::from(Span::styled(size_formatted.clone(), primary_style)),
+ Cell::from(Span::styled(tags_col, secondary_style)),
+ Cell::from(Span::styled(release_title, primary_style)),
+ ]
+ };
+
+ Row::new(cells).style(row_style)
})
.collect();
- frame.render_widget(streams_block.clone(), streams_area);
- let inner_streams = streams_block.inner(streams_area);
+ let streams_table = Table::new(table_rows, widths)
+ .header(header)
+ .block(streams_block)
+ .row_highlight_style(streams_highlight_style)
+ .highlight_symbol(streams_highlight_symbol);
- if inner_streams.height >= 2 {
- let stream_chunks =
- Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).split(inner_streams);
-
- let header_spans = stream_table_header_spans(streams_area.width, theme, modal_active);
- frame.render_widget(
- Paragraph::new(ratatui::text::Line::from(header_spans)),
- stream_chunks[0],
- );
-
- let streams_list = List::new(list_items.clone())
- .highlight_style(streams_highlight_style)
- .highlight_symbol(streams_highlight_symbol);
-
- frame.render_stateful_widget(
- streams_list,
- stream_chunks[1],
- &mut state.resource_list_state,
- );
- } else {
- let streams_list = List::new(list_items)
- .highlight_style(streams_highlight_style)
- .highlight_symbol(streams_highlight_symbol);
-
- frame.render_stateful_widget(
- streams_list,
- inner_streams,
- &mut state.resource_list_state,
- );
- }
+ frame.render_stateful_widget(streams_table, streams_area, &mut state.resource_list_state);
render_scroll_indicator(
frame,
@@ -1535,7 +1627,7 @@ pub fn clean_stream_release_title(filename: &str) -> String {
fn pane_title(
label: &str,
count: usize,
- pane: crate::tui::state::DetailsPane,
+ _pane: crate::tui::state::DetailsPane,
focused: bool,
state: &AppState,
max_width: u16,
@@ -1546,45 +1638,16 @@ fn pane_title(
} else {
""
};
- let mut panes = Vec::new();
- let has_languages = state
- .selected_details
- .as_ref()
- .is_some_and(|d| d.has_languages());
- if has_languages {
- panes.push(crate::tui::state::DetailsPane::Languages);
- }
- if !state.available_seasons.is_empty() {
- panes.push(crate::tui::state::DetailsPane::Seasons);
- panes.push(crate::tui::state::DetailsPane::Episodes);
- }
- panes.push(crate::tui::state::DetailsPane::Streams);
-
- let position_str = if focused && !modal_active && panes.len() > 1 {
- if let Some(position) = panes.iter().position(|candidate| *candidate == pane) {
- format!(" {}/{}", position + 1, panes.len())
- } else {
- String::new()
- }
- } else {
- String::new()
- };
-
let count_suffix = if count > 0 {
format!(" ({count})")
} else {
String::new()
};
- let title_full = format!(" {marker}{label}{count_suffix}{position_str} ");
+ let title_full = format!(" {marker}{label}{count_suffix} ");
let avail = max_width.saturating_sub(2) as usize;
let title = if avail > 0 && crate::tui::text::width(&title_full) > avail {
- let title_medium = format!(" {marker}{label}{count_suffix} ");
- if crate::tui::text::width(&title_medium) <= avail {
- title_medium
- } else {
- format!(" {marker}{label} ")
- }
+ format!(" {marker}{label} ")
} else {
title_full
};
@@ -1655,7 +1718,7 @@ fn selection_style(focused: bool, basic_terminal: bool, theme: &Theme) -> Style
}
fn focus_title_marker(basic_terminal: bool) -> &'static str {
- if basic_terminal { "> " } else { "● " }
+ if basic_terminal { "> " } else { "› " }
}
fn selection_symbol(_focused: bool, _basic_terminal: bool) -> &'static str {
@@ -1791,32 +1854,6 @@ fn render_workflow(
);
}
-fn stream_table_header_spans(width: u16, theme: &Theme, modal_active: bool) -> Vec<Span<'static>> {
- let header_style = if modal_active {
- theme.muted
- } else {
- theme.subtext1.add_modifier(Modifier::BOLD)
- };
- if width < 58 {
- vec![Span::styled(" RES SIZE RELEASE", header_style)]
- } else if width < 85 {
- vec![Span::styled(
- " RES SIZE CODEC RELEASE",
- header_style,
- )]
- } else if width < 115 {
- vec![Span::styled(
- " RES SIZE MEDIA TAGS RELEASE",
- header_style,
- )]
- } else {
- vec![Span::styled(
- " RES SIZE MEDIA TAGS SOURCE RELEASE",
- header_style,
- )]
- }
-}
-
fn footer_group(
key: &'static str,
action: &str,
@@ -2070,6 +2107,104 @@ mod tests {
assert!(content.contains("1.0GB"));
assert!(content.contains("HEVC"));
assert!(content.contains("Pahe.in"));
+
+ let header_line = buffer
+ .content()
+ .chunks(120)
+ .find(|line| {
+ let text: String = line.iter().map(|c| c.symbol()).collect();
+ text.contains("RES") && text.contains("SIZE") && text.contains("SOURCE")
+ })
+ .map(|line| line.iter().map(|c| c.symbol()).collect::<String>())
+ .expect("header line must exist");
+
+ let res_idx = header_line.find("RES").unwrap();
+ let size_idx = header_line.find("SIZE").unwrap();
+ let tags_idx = header_line.find("MEDIA TAGS").unwrap();
+ let source_idx = header_line.find("SOURCE").unwrap();
+ let release_idx = header_line.find("RELEASE").unwrap();
+ assert_eq!(size_idx - res_idx, 9);
+ assert_eq!(tags_idx - size_idx, 10);
+ assert_eq!(source_idx - tags_idx, 19);
+ assert_eq!(release_idx - source_idx, 17);
+
+ let data_line = buffer
+ .content()
+ .chunks(120)
+ .find(|line| {
+ let text: String = line.iter().map(|c| c.symbol()).collect();
+ text.contains("1080p") && text.contains("1.0GB")
+ })
+ .map(|line| line.iter().map(|c| c.symbol()).collect::<String>())
+ .expect("data line must exist");
+ let data_size_idx = data_line.find("1.0GB").unwrap();
+ assert_eq!(data_size_idx, size_idx);
+ }
+
+ #[test]
+ fn test_redundant_source_labels_fallback_to_provider_origin() {
+ let backend = ratatui::backend::TestBackend::new(120, 30);
+ let mut terminal = ratatui::Terminal::new(backend).unwrap();
+ let mut state = AppState {
+ selected_details: Some(MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "test_show".to_string(),
+ },
+ title: "Test Show".to_string(),
+ media_type: MediaType::Series,
+ year: Some("2024".to_string()),
+ description: None,
+ tagline: None,
+ imdb_rating: None,
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: None,
+ genres: vec![],
+ seasons: vec![],
+ dubs: vec![],
+ }),
+ selected_resources: vec![Release {
+ provider: ProviderKind::MovieBox,
+ filename: "Summer Dress S01E02 Multi-Res hevc".to_string(),
+ quality: Some("multi".to_string()),
+ codec: Some("hevc".to_string()),
+ language: None,
+ size_bytes: Some(400 * 1024 * 1024),
+ season: Some(1),
+ episode: Some(2),
+ mirrors: vec![SourceMirror {
+ label: "Multi-Res hevc".to_string(),
+ resolver_url: "https://example.com/stream.mpd".to_string(),
+ headers: vec![],
+ direct_file: true,
+ }],
+ resource_id: None,
+ }],
+ details_pane: crate::tui::state::DetailsPane::Streams,
+ ..Default::default()
+ };
+ let theme = Theme::dracula();
+
+ terminal
+ .draw(|frame| {
+ draw(frame, frame.area(), &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let content = buffer
+ .content()
+ .iter()
+ .map(|cell| cell.symbol())
+ .collect::<String>();
+
+ assert!(content.contains("MovieBox CDN"));
+ assert!(!content.contains("Multi-Res hevc"));
+ assert!(content.contains("Summer Dress S01E02"));
}
#[test]
@@ -2367,9 +2502,9 @@ mod tests {
.iter()
.map(|cell| cell.symbol())
.collect::<String>();
- assert!(content.contains("EP 01"));
- assert!(content.contains("EP 02"));
- assert!(content.contains("EP 10"));
+ assert!(content.contains("Episode 01"));
+ assert!(content.contains("Episode 02"));
+ assert!(content.contains("Episode 10"));
assert!(!content.contains("· ·"));
assert!(!content.contains("· EP"));
}
@@ -2490,14 +2625,14 @@ mod tests {
};
let title_wide = pane_title("Audio", 2, DetailsPane::Languages, true, &state, 40, false);
- assert_eq!(title_wide.to_string(), " ● Audio (2) 1/2 ");
+ assert_eq!(title_wide.to_string(), " › Audio (2) ");
let title_unfocused =
pane_title("Audio", 2, DetailsPane::Languages, false, &state, 40, false);
assert_eq!(title_unfocused.to_string(), " Audio (2) ");
let title_narrow = pane_title("Audio", 2, DetailsPane::Languages, true, &state, 10, false);
- assert_eq!(title_narrow.to_string(), " ● Audio ");
+ assert_eq!(title_narrow.to_string(), " › Audio ");
}
#[test]
fn test_details_screen_renders_in_narrow_terminal_without_clipping() {
@@ -2660,7 +2795,8 @@ mod tests {
assert!(content.contains("Ek Deewane Ki Deewaniyat"));
assert!(content.contains("2025"));
assert!(content.contains("Movie"));
- assert!(content.contains("Audio: 2 Tracks"));
+ assert!(content.contains("Audio (2)"));
+ assert!(content.contains("Original"));
assert!(content.contains("MovieBox"));
assert!(content.contains("No Art"));
}
@@ -2857,7 +2993,8 @@ mod tests {
.map(|cell| cell.symbol())
.collect::<String>();
- assert!(content.contains("Audio: 4 Tracks"));
+ assert!(content.contains("Audio (4)"));
+ assert!(!content.contains("Audio: 4 Tracks"));
assert!(!content.contains("Audio: Original, Hindi, Spanish (LA), Portuguese (BR)"));
}
@@ -2970,7 +3107,7 @@ mod tests {
.collect::<String>();
assert!(content.contains("Confirm Episode Download"));
- assert!(!content.contains("● Streams"));
+ assert!(!content.contains("› Streams"));
assert!(content.contains("Multi"));
assert!(content.contains("Hindi"));
diff --git a/src/tui/screens/help.rs b/src/tui/screens/help.rs
index 54371a4..1a1d694 100644
--- a/src/tui/screens/help.rs
+++ b/src/tui/screens/help.rs
@@ -1,16 +1,16 @@
-use crate::tui::{state::AppState, theme::Theme};
+use crate::tui::{overlay, state::AppState, theme::Theme, widgets::ModalFrame};
use ratatui::{
Frame,
- layout::{Alignment, Rect},
+ layout::{Alignment, Constraint, Layout, Rect},
style::Modifier,
text::{Line, Span},
- widgets::{Block, Borders, Paragraph},
+ widgets::Paragraph,
};
fn help_row(key: &str, desc: &str, theme: &Theme) -> Line<'static> {
Line::from(vec![
Span::styled(
- format!(" {:<17} ", key),
+ format!(" {:<15} ", key),
theme.header.add_modifier(Modifier::BOLD),
),
Span::styled(desc.to_string(), theme.text),
@@ -32,82 +32,63 @@ pub fn build_help_columns(
let mut right = Vec::new();
left.push(help_section_header("Navigation", theme));
- left.push(help_row(
- "[↑] [↓] / [k] [j]",
- "Scroll & Navigate Lists",
- theme,
- ));
- left.push(help_row(
- "[←] [→] / [Tab]",
- "Switch Panes / Step Grid",
- theme,
- ));
- left.push(help_row("[Home] / [End]", "Top / Bottom of List", theme));
- left.push(help_row("[PgUp] / [PgDn]", "Page Up / Down", theme));
- left.push(help_row("[Esc] / [c]", "Back / Clear Search", theme));
- left.push(help_row(
- "[Ctrl+U] / [W]",
- "Clear Line / Delete Word",
- theme,
- ));
+ left.push(help_row("↑ / ↓", "Navigate rows & lists", theme));
+ left.push(help_row("← / →", "Step search card columns", theme));
+ left.push(help_row("Tab / S-Tab", "Switch tabs & detail panes", theme));
+ left.push(help_row("Home / End", "Jump to start / end of list", theme));
+ left.push(help_row("PgUp / PgDn", "Scroll one page up / down", theme));
+ left.push(help_row("Esc / c", "Clear search / back / dismiss", theme));
+ left.push(help_row("Ctrl+U", "Clear entire search input", theme));
+ left.push(help_row("Ctrl+W", "Delete previous word", theme));
left.push(Line::from(""));
if state.is_tv_mode {
left.push(help_section_header("TV Actions", theme));
- left.push(help_row("[Enter]", "Play Selected Channel", theme));
- left.push(help_row("[r]", "Reload M3U Playlists", theme));
- left.push(help_row("/list", "Show All TV Channels", theme));
- } else if state.active_provider == crate::providers::models::ProviderKind::Addons {
- left.push(help_section_header("Addon Actions", theme));
- left.push(help_row("[Enter]", "Select Title / Play Stream", theme));
- left.push(help_row("[d]", "Download Video Stream", theme));
- left.push(help_row("[f]", "Favorite / Unfavorite Title", theme));
- left.push(help_row("[s]", "Subtitles Picker (Details)", theme));
- left.push(help_row("[r]", "Refresh Catalog / Streams", theme));
+ left.push(help_row("Enter", "Play selected channel", theme));
+ left.push(help_row("d / Delete", "Delete selected playlist", theme));
+ left.push(help_row("r", "Reload M3U playlists", theme));
+ left.push(help_row("/list", "Browse all TV channels", theme));
} else {
left.push(help_section_header("Streaming Actions", theme));
- left.push(help_row("[Enter]", "Play with Default Player", theme));
- left.push(help_row("[d]", "Download Episode / Season", theme));
- left.push(help_row("[f]", "Favorite / Unfavorite Title", theme));
- left.push(help_row("[s]", "Subtitles Picker (Details)", theme));
+ left.push(help_row("Enter", "Play selected release", theme));
+ left.push(help_row("Space / P", "Direct resume playback", theme));
+ left.push(help_row("d / Delete", "Download or remove history", theme));
+ left.push(help_row("f", "Favorite / unfavorite title", theme));
left.push(help_row(
- "[Ctrl+P]",
- &format!("Switch Provider ({})", state.active_provider.label()),
+ "Ctrl+P",
+ &format!("Cycle provider ({})", state.active_provider.label()),
theme,
));
- left.push(help_row("[r]", "Refresh Results / Streams", theme));
+ left.push(help_row("r", "Refresh active results", theme));
}
+
right.push(help_section_header("Content Modes", theme));
if state.streaming_enabled {
- let key = format!("[{}]", crate::tui::text::CTRL_S_STR);
- right.push(help_row(&key, "Switch to Streaming Mode", theme));
+ let key = crate::tui::text::CTRL_S_STR;
+ right.push(help_row(key, "Switch to Streaming Mode", theme));
}
if state.tv_enabled {
- let key = format!("[{}]", crate::tui::text::CTRL_T_STR);
- right.push(help_row(&key, "Switch to Live TV Mode", theme));
+ let key = crate::tui::text::CTRL_T_STR;
+ right.push(help_row(key, "Switch to Live TV Mode", theme));
}
right.push(Line::from(""));
right.push(help_section_header("Commands & Shortcuts", theme));
- right.push(help_row("/settings", "Preferences, Themes & Modes", theme));
+ right.push(help_row("/settings", "Preferences & maintenance", theme));
if state.is_tv_mode {
- right.push(help_row("/list", "Show All TV Channels", theme));
+ right.push(help_row("/list", "Browse all TV channels", theme));
} else if state.active_provider == crate::providers::models::ProviderKind::Addons {
- right.push(help_row("/browse", "Browse Addon Catalogs", theme));
+ right.push(help_row("/browse", "Browse addon catalogs", theme));
} else {
- right.push(help_row("/browse", "Browse Curated Categories", theme));
+ right.push(help_row("/browse", "Browse curated genres", theme));
}
if !state.is_tv_mode {
- right.push(help_row(
- "/history",
- "Watch History ([Space] Resume)",
- theme,
- ));
- right.push(help_row("/favorites", "Starred Titles", theme));
+ right.push(help_row("/history", "Watch history & resume", theme));
+ right.push(help_row("/favorites", "Starred media library", theme));
}
- right.push(help_row("/clear", "Clear Search Results", theme));
- right.push(help_row("/exit", "Exit App ([q] / Ctrl+C)", theme));
- right.push(help_row("[?]", "Toggle This Help Menu", theme));
+ right.push(help_row("/clear", "Clear search query & results", theme));
+ right.push(help_row("/exit", "Exit app (q / Ctrl+C)", theme));
+ right.push(help_row("?", "Toggle this help menu", theme));
(left, right)
}
@@ -121,48 +102,36 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
let (left_col, right_col) = build_help_columns(state, theme);
- let mut all_lines = left_col.clone();
- all_lines.push(Line::from(""));
- all_lines.extend(right_col.clone());
-
- let left_width = left_col.iter().map(Line::width).max().unwrap_or(40);
- let right_width = right_col.iter().map(Line::width).max().unwrap_or(40);
+ let left_width = left_col.iter().map(Line::width).max().unwrap_or(36);
+ let right_width = right_col.iter().map(Line::width).max().unwrap_or(36);
let content_width = left_width.max(right_width) as u16;
let max_lines = left_col.len().max(right_col.len());
let capacity = area.height.saturating_sub(6).max(4) as usize;
- let two_columns = area.width >= 102 && capacity >= max_lines.saturating_sub(4);
+ let two_columns = area.width >= 78 && capacity >= max_lines.saturating_sub(2);
+
+ let mut all_lines = left_col.clone();
+ all_lines.push(Line::from(""));
+ all_lines.extend(right_col.clone());
if !two_columns && all_lines.len() > capacity {
let max_scroll = all_lines.len().saturating_sub(capacity);
let scroll = state.help_scroll.min(max_scroll);
let window: Vec<Line> = all_lines[scroll..scroll + capacity.min(all_lines.len())].to_vec();
let position = if max_scroll > 0 {
- format!(" · {}/{scroll_max}", scroll + 1, scroll_max = max_scroll)
+ format!(" · {}/{}", scroll + 1, max_scroll)
} else {
String::new()
};
- let title = format!(" Help · {mode_title}{position} ");
- let block = Block::default()
- .title(title)
- .title_alignment(Alignment::Center)
- .title_style(theme.title)
- .borders(Borders::ALL)
- .border_type(crate::tui::overlay::border_type(state.basic_terminal))
- .border_style(theme.border_focus);
- let p = Paragraph::new(window)
- .block(block)
- .alignment(Alignment::Left);
- let popup_chunk = crate::tui::overlay::centered(
- area,
- (content_width + 8).min(area.width.saturating_sub(2)),
- capacity as u16 + 2,
- 46,
- 120,
- );
- crate::tui::overlay::clear_modal_area(frame, area, popup_chunk, theme);
- frame.render_widget(p, popup_chunk);
+ let title = format!("Help · {mode_title}{position}");
+ let desired_w = (content_width + 8).min(area.width.saturating_sub(2));
+ let desired_h = capacity as u16 + 2;
+ let popup_chunk = overlay::help_modal_layout(area, desired_w, desired_h);
+ let inner =
+ ModalFrame::new(&title, theme, state.basic_terminal).render(frame, popup_chunk, area);
+ let p = Paragraph::new(window).alignment(Alignment::Left);
+ frame.render_widget(p, inner);
return;
}
@@ -178,28 +147,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
(all_lines.len() as u16 + 2).min(area.height.saturating_sub(2))
};
- let popup_chunk = crate::tui::overlay::centered(area, desired_width, desired_height, 46, 120);
-
- crate::tui::overlay::clear_modal_area(frame, area, popup_chunk, theme);
-
- let title = format!(" Help · {mode_title} ");
- let block = Block::default()
- .title(title)
- .title_alignment(Alignment::Center)
- .title_style(theme.title)
- .borders(Borders::ALL)
- .border_type(crate::tui::overlay::border_type(state.basic_terminal))
- .border_style(theme.border_focus);
+ let popup_chunk = overlay::help_modal_layout(area, desired_width, desired_height);
+ let title = format!("Help · {mode_title}");
+ let inner =
+ ModalFrame::new(&title, theme, state.basic_terminal).render(frame, popup_chunk, area);
if two_columns {
- let inner = block.inner(popup_chunk);
- frame.render_widget(block, popup_chunk);
-
- let chunks = ratatui::layout::Layout::horizontal([
- ratatui::layout::Constraint::Percentage(50),
- ratatui::layout::Constraint::Percentage(50),
- ])
- .split(inner);
+ let chunks = Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)])
+ .split(inner);
frame.render_widget(
Paragraph::new(left_col).alignment(Alignment::Left),
@@ -210,14 +165,10 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
chunks[1],
);
} else {
- let p = Paragraph::new(all_lines)
- .block(block)
- .alignment(Alignment::Left);
-
- frame.render_widget(p, popup_chunk);
+ let p = Paragraph::new(all_lines).alignment(Alignment::Left);
+ frame.render_widget(p, inner);
}
}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -241,8 +192,8 @@ mod tests {
assert!(left_text.contains("Navigation"));
assert!(left_text.contains("Streaming Actions"));
- assert!(left_text.contains("Play with Default Player"));
- assert!(left_text.contains("Download Episode / Season"));
+ assert!(left_text.contains("Play selected release"));
+ assert!(left_text.contains("Download or remove history"));
assert!(right_text.contains("Content Modes"));
assert!(right_text.contains("Commands & Shortcuts"));
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index e295482..b1b8fd8 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -6,7 +6,7 @@ use crate::tui::{
use ratatui::{
Frame,
layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
- style::{Color, Modifier, Style},
+ style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
};
@@ -46,10 +46,6 @@ fn search_view_state(state: &AppState) -> SearchViewState {
}
}
-pub(crate) fn slash_command_description(cmd: &str, state: &AppState) -> Option<&'static str> {
- crate::tui::commands::SlashCommand::description_for(cmd, state)
-}
-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HomeLayoutTier {
Compact,
@@ -502,38 +498,50 @@ pub(crate) fn render_landing_deck(frame: &mut Frame, area: Rect, state: &AppStat
};
let mut title_spans: Vec<Span> = Vec::new();
- let (active_style, inactive_style, hint_style, sep_style) = if modal_active {
- (theme.muted, theme.muted, theme.muted, theme.muted)
- } else {
- (
- if is_focused {
- theme.title.add_modifier(Modifier::BOLD)
- } else {
- theme.text.add_modifier(Modifier::BOLD)
- },
- theme.subtext1,
- theme.text_dim,
- theme.surface1,
- )
- };
+ let (active_style, inactive_style, hint_bracket_style, hint_key_style, sep_style) =
+ if modal_active {
+ (
+ theme.muted,
+ theme.muted,
+ theme.muted,
+ theme.muted,
+ theme.muted,
+ )
+ } else {
+ (
+ if is_focused {
+ theme.title.add_modifier(Modifier::BOLD)
+ } else {
+ theme.text.add_modifier(Modifier::BOLD)
+ },
+ theme.subtext1,
+ theme.overlay0,
+ theme.shortcut,
+ theme.surface1,
+ )
+ };
if has_cw && has_fav {
let sep = if state.basic_terminal { " | " } else { " │ " };
match tab {
crate::tui::state::HomeDeckTab::ContinueWatching => {
- title_spans.push(Span::styled(" Continue Watching ", active_style));
+ title_spans.push(Span::styled(" Resume ", active_style));
title_spans.push(Span::styled(sep, sep_style));
- title_spans.push(Span::styled("Favorites", inactive_style));
- title_spans.push(Span::styled(" (Tab) ", hint_style));
+ title_spans.push(Span::styled("Favorites ", inactive_style));
+ title_spans.push(Span::styled("[", hint_bracket_style));
+ title_spans.push(Span::styled("Tab", hint_key_style));
+ title_spans.push(Span::styled("] ", hint_bracket_style));
}
crate::tui::state::HomeDeckTab::Favorites => {
- title_spans.push(Span::styled(" Continue Watching", inactive_style));
- title_spans.push(Span::styled(" (Tab)", hint_style));
+ title_spans.push(Span::styled(" Resume ", inactive_style));
+ title_spans.push(Span::styled("[", hint_bracket_style));
+ title_spans.push(Span::styled("Tab", hint_key_style));
+ title_spans.push(Span::styled("]", hint_bracket_style));
title_spans.push(Span::styled(sep, sep_style));
title_spans.push(Span::styled(" Favorites ", active_style));
}
}
} else if has_cw {
- title_spans.push(Span::styled(" Continue Watching ", active_style));
+ title_spans.push(Span::styled(" Resume ", active_style));
} else {
title_spans.push(Span::styled(" Favorites ", active_style));
}
@@ -583,11 +591,7 @@ pub(crate) fn render_landing_deck(frame: &mut Frame, area: Rect, state: &AppStat
};
let progress_str = if let Some(rem) = item.formatted_remaining() {
- if let Some(pct) = item.progress_percentage() {
- format!("{:.0}% · {rem}", pct)
- } else {
- rem
- }
+ rem
} else if let Some(pct) = item.progress_percentage() {
format!("{:.0}%", pct)
} else {
@@ -679,8 +683,8 @@ pub(crate) fn render_landing_deck(frame: &mut Frame, area: Rect, state: &AppStat
let pill_style = if state.basic_terminal {
theme.sapphire
} else {
- let bg = theme.surface1.fg.unwrap_or(Color::Rgb(69, 71, 90));
- let fg = theme.sapphire.fg.unwrap_or(Color::Rgb(116, 199, 236));
+ let bg = theme.surface1.fg.unwrap_or(theme.base);
+ let fg = theme.sapphire.fg.unwrap_or(theme.base);
Style::default().bg(bg).fg(fg)
};
let pill_area = Rect {
@@ -898,8 +902,8 @@ fn render_search_bar(
let style = if state.basic_terminal {
theme.sapphire.add_modifier(Modifier::BOLD)
} else {
- let bg = theme.surface1.fg.unwrap_or(Color::Rgb(69, 71, 90));
- let fg = theme.sapphire.fg.unwrap_or(Color::Rgb(116, 199, 236));
+ let bg = theme.surface1_color();
+ let fg = theme.sapphire.fg.unwrap_or(theme.base);
Style::default().bg(bg).fg(fg).add_modifier(Modifier::BOLD)
};
(text, style)
@@ -947,8 +951,8 @@ fn render_search_bar(
let style = if state.basic_terminal {
theme.lavender
} else {
- let bg = theme.surface1.fg.unwrap_or(Color::Rgb(69, 71, 90));
- let fg = theme.lavender.fg.unwrap_or(Color::Rgb(180, 190, 254));
+ let bg = theme.surface1_color();
+ let fg = theme.lavender.fg.unwrap_or(theme.base);
Style::default().bg(bg).fg(fg)
};
(text, style)
@@ -957,8 +961,8 @@ fn render_search_bar(
let style = if state.basic_terminal {
theme.teal
} else {
- let bg = theme.surface1.fg.unwrap_or(Color::Rgb(69, 71, 90));
- let fg = theme.teal.fg.unwrap_or(Color::Rgb(148, 226, 213));
+ let bg = theme.surface1_color();
+ let fg = theme.teal.fg.unwrap_or(theme.base);
Style::default().bg(bg).fg(fg)
};
(text, style)
@@ -973,8 +977,8 @@ fn render_search_bar(
let style = if state.basic_terminal {
theme.sapphire
} else {
- let bg = theme.surface1.fg.unwrap_or(Color::Rgb(69, 71, 90));
- let fg = theme.sapphire.fg.unwrap_or(Color::Rgb(116, 199, 236));
+ let bg = theme.surface1_color();
+ let fg = theme.sapphire.fg.unwrap_or(theme.base);
Style::default().bg(bg).fg(fg)
};
(text, style)
@@ -1379,7 +1383,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
height: vertical_chunks[rows.search].height,
};
- if !state.tv_config_popup && !update_active && !state.show_settings_popup {
+ if !state.tv_config_popup
+ && !update_active
+ && !state.show_settings_popup
+ && !state.show_help
+ {
render_search_bar(frame, search_card_area, state, theme, view, true);
}
search_bar_area = search_card_area;
@@ -1413,21 +1421,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
return;
}
- let chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(1),
- Constraint::Length(1),
- Constraint::Min(0),
- ])
- .split(area);
- let results_chunk = chunks[2];
- search_bar_area = Rect {
- x: chunks[0].x + 2,
- width: chunks[0].width.saturating_sub(4),
- ..chunks[0]
- };
- render_search_bar(frame, search_bar_area, state, theme, view, false);
+ let (search_bar_area_calc, results_chunk) = search_results_layout(area);
+ search_bar_area = search_bar_area_calc;
+ if !state.show_help {
+ render_search_bar(frame, search_bar_area, state, theme, view, false);
+ }
let list_block = Block::default();
if !state.search_results.is_empty() {
let initial_metrics = state.result_metrics(results_chunk.height, results_chunk.width);
@@ -1633,6 +1631,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
theme,
state.basic_terminal,
modal_active,
+ is_active_selection,
)
});
let badge_width = badge_spans.as_ref().map_or(0, |spans| {
@@ -1702,14 +1701,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if is_history {
if !type_tag.is_empty() {
row2_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
- row2_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ row2_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
}
if res.season > 0 {
row2_spans.push(ratatui::text::Span::styled(
format!("S{:02}E{:02}", res.season, res.episode),
theme.text,
));
- row2_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ row2_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
}
if let Some(hist) = state.history.get_item(
@@ -1743,14 +1742,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if use_three_rows {
row3_spans.extend(progress_spans);
- row3_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ row3_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
row3_spans.push(ratatui::text::Span::styled(
format!("Watched {}", hist.formatted_relative_time()),
theme.text_dim,
));
} else {
row2_spans.extend(progress_spans);
- row2_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ row2_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
}
} else if hist.completed {
let comp_span = ratatui::text::Span::styled(
@@ -1763,14 +1762,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
);
if use_three_rows {
row3_spans.push(comp_span);
- row3_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ row3_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
row3_spans.push(ratatui::text::Span::styled(
format!("Watched {}", hist.formatted_relative_time()),
theme.text_dim,
));
} else {
row2_spans.push(comp_span);
- row2_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ row2_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
}
}
}
@@ -1791,31 +1790,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let star = if state.basic_terminal { "* " } else { "★ " };
row2_spans.push(ratatui::text::Span::styled(star, theme.rating));
row2_spans.push(ratatui::text::Span::styled(r, theme.text));
- row2_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
- }
-
- let genre_buf = meta.genres.join(", ");
- if !genre_buf.is_empty() {
- let g_trunc = crate::tui::text::truncate_width(
- &genre_buf,
- text_area.width.saturating_sub(2) as usize,
- )
- .into_owned();
- row3_spans
- .push(ratatui::text::Span::styled(g_trunc, theme.subtext1));
+ row2_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
}
}
- } else if is_selected && state.preview_loading {
- let dots = match (state.tick_count / 4) % 4 {
- 0 => "",
- 1 => ".",
- 2 => "..",
- _ => "...",
- };
- row3_spans.push(ratatui::text::Span::styled(
- format!("Loading{dots}"),
- theme.text_dim,
- ));
}
let has_year = res.release_year != "Unknown" && !res.release_year.is_empty();
if has_year {
@@ -1828,7 +1805,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
},
));
row2_spans.push(ratatui::text::Span::styled(
- " • ",
+ " ",
if modal_active {
theme.muted
} else {
@@ -1846,21 +1823,43 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
theme.text
},
));
- row2_spans.push(ratatui::text::Span::styled(
- " • ",
- if modal_active {
- theme.muted
- } else {
- theme.text_dim
- },
- ));
}
- row2_spans.push(crate::tui::widgets::badge::provider_badge_span(
+
+ row3_spans.push(crate::tui::widgets::badge::provider_badge_span(
res.provider,
theme,
state.basic_terminal,
modal_active,
));
+
+ if let Some(meta) = matching_meta {
+ if is_selected {
+ let genre_buf = meta.genres.join(", ");
+ if !genre_buf.is_empty() {
+ row3_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
+ let available_w = (text_area.width as usize).saturating_sub(
+ crate::tui::text::width(res.provider.label()) + 6,
+ );
+ let g_trunc =
+ crate::tui::text::truncate_width(&genre_buf, available_w)
+ .into_owned();
+ row3_spans
+ .push(ratatui::text::Span::styled(g_trunc, theme.subtext1));
+ }
+ }
+ } else if is_selected && state.preview_loading {
+ let dots = match (state.tick_count / 4) % 4 {
+ 0 => "",
+ 1 => ".",
+ 2 => "..",
+ _ => "...",
+ };
+ row3_spans.push(ratatui::text::Span::styled(" ", theme.text_dim));
+ row3_spans.push(ratatui::text::Span::styled(
+ format!("Loading{dots}"),
+ theme.text_dim,
+ ));
+ }
}
if text_layout[2].height > 0 && row2_spans.len() > 1 {
@@ -1896,7 +1895,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
}
- if !state.tv_config_popup && !state.show_settings_popup {
+ if !state.tv_config_popup && !state.show_settings_popup && !state.show_help {
render_search_suggestions(frame, area, search_bar_area, state, theme, view);
}
render_provider_popup(frame, area, search_bar_area, state, theme);
@@ -2332,7 +2331,7 @@ fn render_search_suggestions(
suggestion.as_str()
};
- let desc = slash_command_description(suggestion, state);
+ let desc = crate::tui::commands::SlashCommand::description_for(suggestion, state);
let text_style = if is_selected {
theme.highlight.add_modifier(Modifier::BOLD)
} else {
@@ -2545,6 +2544,30 @@ fn render_provider_popup(
frame.render_stateful_widget(list, inner_area, &mut list_state);
}
+pub fn search_results_layout(area: Rect) -> (Rect, Rect) {
+ let top_pad = if area.height >= 14 { 1 } else { 0 };
+ let chunks = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([
+ Constraint::Length(top_pad),
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Min(0),
+ ])
+ .split(area);
+ let search_bar_area = Rect {
+ x: chunks[1].x + 2,
+ width: chunks[1].width.saturating_sub(4),
+ ..chunks[1]
+ };
+ let results_chunk = Rect {
+ x: chunks[3].x + 2,
+ width: chunks[3].width.saturating_sub(4),
+ ..chunks[3]
+ };
+ (search_bar_area, results_chunk)
+}
+
#[inline(always)]
fn item_slot_rects(item_area: Rect, poster_width: u16) -> (Rect, Rect) {
if poster_width == 0 {
@@ -3169,12 +3192,12 @@ mod tests {
rendered.push('\n');
}
- assert!(rendered.contains("Continue Watching"));
+ assert!(rendered.contains("Resume"));
assert!(rendered.contains("Favorites"));
- assert!(rendered.contains("(Tab)"));
+ assert!(rendered.contains("[Tab]"));
assert!(rendered.contains("Severance"));
assert!(rendered.contains("S01E03"));
- assert!(rendered.contains("40%"));
+ assert!(rendered.contains("30m left"));
}
#[test]
@@ -3574,6 +3597,43 @@ mod tests {
);
}
#[test]
+ fn test_search_results_aligned_with_search_bar() {
+ let backend = TestBackend::new(100, 30);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let mut state = AppState {
+ input_mode: InputMode::Normal,
+ search_query: "Matrix".into(),
+ search_results: vec![crate::models::SearchResult {
+ id: "test_1".into(),
+ title: "The Matrix".into(),
+ stype: 1,
+ release_year: "1999".into(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: crate::providers::models::ProviderKind::MovieBox,
+ }],
+ has_search_settled: true,
+ basic_terminal: false,
+ ..Default::default()
+ };
+ state.search_list_state.select(Some(0));
+ let theme = Theme::mocha();
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 100, 30);
+ draw(frame, area, &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ assert_eq!(buffer[(0, 1)].symbol(), " ");
+ assert_eq!(buffer[(1, 1)].symbol(), " ");
+ assert_eq!(buffer[(2, 1)].symbol(), "❯");
+ assert_eq!(buffer[(0, 3)].symbol(), " ");
+ assert_eq!(buffer[(1, 3)].symbol(), " ");
+ }
+ #[test]
fn test_search_result_selection_indicator_basic_terminal() {
let backend = TestBackend::new(100, 30);
let mut terminal = Terminal::new(backend).unwrap();
diff --git a/src/tui/state.rs b/src/tui/state.rs
index fee82ae..c0cf607 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -78,7 +78,7 @@ impl SettingsCategory {
Self::General => 3,
Self::ContentModes => 3,
Self::Appearance => 1,
- Self::StorageInfo => 4,
+ Self::StorageInfo => 5,
}
}
pub fn next(self) -> Self {
@@ -251,7 +251,7 @@ pub struct AppState {
pub stream_error: Option<String>,
pub details_error: Option<String>,
pub preview_cache: lru::LruCache<String, MediaDetails>,
- pub resource_list_state: ListState,
+ pub resource_list_state: TableState,
pub details_pane: DetailsPane,
pub selected_season: usize,
@@ -421,7 +421,7 @@ impl Default for AppState {
auto_play_on_ready: false,
stream_error: None,
details_error: None,
- resource_list_state: ListState::default(),
+ resource_list_state: TableState::default(),
preview_cache: lru::LruCache::new(cache_capacity(64)),
details_pane: DetailsPane::default(),
selected_season: 1,
@@ -662,6 +662,58 @@ impl AppState {
title: impl Into<String>,
message: impl Into<String>,
) {
+ let title = title.into();
+ let message = message.into();
+
+ let same_category = |a: &str, b: &str| -> bool {
+ if a.eq_ignore_ascii_case(b) {
+ return true;
+ }
+ let is_playback = |s: &str| {
+ s.eq_ignore_ascii_case("Playback")
+ || s.eq_ignore_ascii_case("Preparing playback")
+ || s.eq_ignore_ascii_case("Opening Player")
+ || s.eq_ignore_ascii_case("Playback Cancelled")
+ || s.eq_ignore_ascii_case("Playback unavailable")
+ || s.to_lowercase().contains("player")
+ };
+ let is_download = |s: &str| {
+ s.eq_ignore_ascii_case("Download")
+ || s.eq_ignore_ascii_case("Preparing download")
+ || s.eq_ignore_ascii_case("Download Started")
+ || s.eq_ignore_ascii_case("Download complete")
+ || s.eq_ignore_ascii_case("Cancelling download")
+ || s.eq_ignore_ascii_case("Download failed")
+ || s.to_lowercase().contains("download")
+ };
+ let is_update = |s: &str| {
+ s.eq_ignore_ascii_case("Updates")
+ || s.eq_ignore_ascii_case("Checking for updates")
+ || s.eq_ignore_ascii_case("Up to date")
+ || s.eq_ignore_ascii_case("Update check failed")
+ || s.eq_ignore_ascii_case("Homebrew Upgrade")
+ };
+ let is_cache = |s: &str| {
+ s.eq_ignore_ascii_case("Cache")
+ || s.eq_ignore_ascii_case("Clearing Cache")
+ || s.eq_ignore_ascii_case("Cache Cleared")
+ || s.eq_ignore_ascii_case("Cache Clear Failed")
+ };
+ (is_playback(a) && is_playback(b))
+ || (is_download(a) && is_download(b))
+ || (is_update(a) && is_update(b))
+ || (is_cache(a) && is_cache(b))
+ };
+
+ if let Some(existing) = self
+ .notifications
+ .iter_mut()
+ .find(|n| same_category(&n.title, &title))
+ {
+ *existing = crate::tui::overlay::Notification::new(kind, title, message);
+ return;
+ }
+
if self.notifications.len() >= 3 {
let removable = self
.notifications
@@ -1472,6 +1524,52 @@ mod tests {
assert!(state.favorites_landing_visible());
}
+ #[test]
+ fn test_notify_replaces_same_category_in_place() {
+ let mut state = AppState::default();
+ state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Preparing playback",
+ "Resolving stream...",
+ );
+ assert_eq!(state.notifications.len(), 1);
+ assert_eq!(state.notifications[0].title, "Preparing playback");
+ assert_eq!(state.notifications[0].message, "Resolving stream...");
+
+ state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Playback Cancelled",
+ "Stream launch cancelled.",
+ );
+ assert_eq!(state.notifications.len(), 1);
+ assert_eq!(state.notifications[0].title, "Playback Cancelled");
+ assert_eq!(state.notifications[0].message, "Stream launch cancelled.");
+
+ state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Opening Player",
+ "Launching mpv.",
+ );
+ assert_eq!(state.notifications.len(), 1);
+ assert_eq!(state.notifications[0].title, "Opening Player");
+
+ state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Preparing download",
+ "Waiting for details...",
+ );
+ assert_eq!(state.notifications.len(), 2);
+ assert_eq!(state.notifications[1].title, "Preparing download");
+
+ state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Download Started",
+ "Started: Movie.mkv",
+ );
+ assert_eq!(state.notifications.len(), 2);
+ assert_eq!(state.notifications[1].title, "Download Started");
+ }
+
#[test]
fn test_cycle_settings_player_dynamic_detection() {
let mut state = AppState {
diff --git a/src/tui/theme.rs b/src/tui/theme.rs
index eb2875d..f3a0916 100644
--- a/src/tui/theme.rs
+++ b/src/tui/theme.rs
@@ -92,7 +92,6 @@ pub struct Theme {
pub sapphire: Style,
pub subtext1: Style,
pub base: Color,
- pub bg: Style,
pub rosewater: Style,
pub flamingo: Style,
pub maroon: Style,
@@ -122,7 +121,7 @@ pub enum ColorSupport {
}
impl ColorSupport {
pub fn current() -> Self {
- if std::env::var("NO_COLOR").is_ok() {
+ if std::env::var("NO_COLOR").is_ok_and(|v| !v.is_empty()) {
return ColorSupport::NoColor;
}
if std::env::var("WT_SESSION").is_ok() {
@@ -164,7 +163,10 @@ pub(crate) fn classify_terminal(colorterm: &str, term: &str, term_program: &str)
|| term_program == "ghostty"
|| term_program == "konsole"
|| term_program == "xfce4-terminal"
- || std::env::var("VTE_VERSION").is_ok()
+ || std::env::var("VTE_VERSION")
+ .ok()
+ .and_then(|v| v.parse::<u32>().ok())
+ .is_some_and(|v| v >= 3600)
|| std::env::var("WEZTERM_EXECUTABLE").is_ok()
|| std::env::var("ALACRITTY_WINDOW_ID").is_ok()
|| std::env::var("TILIX_ID").is_ok();
@@ -216,7 +218,6 @@ impl Theme {
sapphire: Style::default().fg(cp(116, 199, 236)),
subtext1: Style::default().fg(cp(186, 194, 222)),
base: cp(30, 30, 46),
- bg: Style::default(),
rosewater: Style::default().fg(cp(245, 224, 220)),
flamingo: Style::default().fg(cp(242, 205, 205)),
maroon: Style::default().fg(cp(235, 160, 172)),
@@ -235,33 +236,32 @@ impl Theme {
pub fn latte() -> Self {
Self {
border: Style::default().fg(cp(140, 143, 161)),
- border_focus: Style::default().fg(cp(30, 102, 245)),
+ border_focus: Style::default().fg(cp(20, 80, 200)),
text: Style::default().fg(cp(76, 79, 105)),
text_dim: Style::default().fg(cp(108, 111, 133)),
title: Style::default()
.fg(cp(136, 57, 239))
.add_modifier(Modifier::BOLD),
highlight: Style::default()
- .fg(cp(30, 102, 245))
+ .fg(cp(20, 80, 200))
.add_modifier(Modifier::BOLD),
header: Style::default()
.fg(cp(234, 118, 203))
.add_modifier(Modifier::BOLD),
error: Style::default().fg(cp(210, 15, 57)),
- success: Style::default().fg(cp(64, 160, 43)),
- shortcut: Style::default().fg(cp(254, 100, 11)),
+ success: Style::default().fg(cp(42, 120, 28)),
+ shortcut: Style::default().fg(cp(168, 66, 0)),
overlay: Style::default().fg(cp(108, 111, 133)),
- rating: Style::default().fg(cp(223, 142, 29)),
+ rating: Style::default().fg(cp(140, 85, 0)),
accent: Style::default()
- .fg(cp(23, 146, 153))
+ .fg(cp(20, 110, 118))
.add_modifier(Modifier::BOLD),
muted: Style::default().fg(cp(108, 111, 133)),
- teal: Style::default().fg(cp(23, 146, 153)),
- lavender: Style::default().fg(cp(114, 135, 253)),
- sapphire: Style::default().fg(cp(32, 159, 181)),
+ teal: Style::default().fg(cp(20, 110, 118)),
+ lavender: Style::default().fg(cp(60, 80, 210)),
+ sapphire: Style::default().fg(cp(22, 111, 125)),
subtext1: Style::default().fg(cp(92, 95, 119)),
base: cp(239, 241, 245),
- bg: Style::default(),
rosewater: Style::default().fg(cp(220, 138, 120)),
flamingo: Style::default().fg(cp(221, 120, 120)),
maroon: Style::default().fg(cp(230, 69, 83)),
@@ -325,7 +325,7 @@ impl Theme {
pub fn detect_with_light(light: Option<bool>) -> Self {
let resolved_light = light.unwrap_or_else(crate::tui::terminal::background_is_light);
- if std::env::var("NO_COLOR").is_ok() {
+ if std::env::var("NO_COLOR").is_ok_and(|v| !v.is_empty()) {
return Self::monochrome(resolved_light);
}
Self::detect_from(ColorSupport::current(), resolved_light)
@@ -372,7 +372,6 @@ impl Theme {
self.sapphire = quantize_style(self.sapphire);
self.subtext1 = quantize_style(self.subtext1);
self.base = to_indexed_256(self.base);
- self.bg = quantize_style(self.bg);
self.rosewater = quantize_style(self.rosewater);
self.flamingo = quantize_style(self.flamingo);
self.maroon = quantize_style(self.maroon);
@@ -414,7 +413,6 @@ impl Theme {
sapphire: Style::default().fg(foreground),
subtext1: Style::default().fg(foreground),
base: Color::Reset,
- bg: Style::default(),
rosewater: Style::default().fg(foreground),
flamingo: Style::default().fg(foreground),
maroon: Style::default().fg(foreground),
@@ -462,7 +460,6 @@ impl Theme {
sapphire: Style::default().fg(Color::Blue),
subtext1: Style::default().fg(Color::Black),
base: Color::White,
- bg: Style::default(),
rosewater: Style::default().fg(Color::Black),
flamingo: Style::default().fg(Color::Magenta),
maroon: Style::default().fg(Color::Red),
@@ -507,7 +504,6 @@ impl Theme {
sapphire: Style::default().fg(Color::Cyan),
subtext1: Style::default().fg(Color::White),
base: Color::Black,
- bg: Style::default(),
rosewater: Style::default().fg(Color::White),
flamingo: Style::default().fg(Color::Magenta),
maroon: Style::default().fg(Color::Red),
@@ -552,7 +548,6 @@ impl Theme {
sapphire: Style::default().fg(cp(125, 196, 228)),
subtext1: Style::default().fg(cp(184, 192, 224)),
base: cp(36, 39, 58),
- bg: Style::default(),
rosewater: Style::default().fg(cp(244, 219, 214)),
flamingo: Style::default().fg(cp(240, 198, 198)),
maroon: Style::default().fg(cp(238, 153, 160)),
@@ -597,7 +592,6 @@ impl Theme {
sapphire: Style::default().fg(cp(133, 193, 220)),
subtext1: Style::default().fg(cp(181, 191, 226)),
base: cp(48, 52, 70),
- bg: Style::default(),
rosewater: Style::default().fg(cp(242, 213, 207)),
flamingo: Style::default().fg(cp(238, 190, 190)),
maroon: Style::default().fg(cp(234, 153, 156)),
@@ -642,7 +636,6 @@ impl Theme {
sapphire: Style::default().fg(cp(94, 129, 172)),
subtext1: Style::default().fg(cp(229, 233, 240)),
base: cp(46, 52, 64),
- bg: Style::default(),
rosewater: Style::default().fg(cp(216, 222, 233)),
flamingo: Style::default().fg(cp(216, 222, 233)),
maroon: Style::default().fg(cp(191, 97, 106)),
@@ -687,7 +680,6 @@ impl Theme {
sapphire: Style::default().fg(cp(125, 207, 255)),
subtext1: Style::default().fg(cp(169, 177, 214)),
base: cp(26, 27, 38),
- bg: Style::default(),
rosewater: Style::default().fg(cp(224, 175, 104)),
flamingo: Style::default().fg(cp(247, 118, 142)),
maroon: Style::default().fg(cp(247, 118, 142)),
@@ -732,7 +724,6 @@ impl Theme {
sapphire: Style::default().fg(cp(139, 233, 253)),
subtext1: Style::default().fg(cp(248, 248, 242)),
base: cp(40, 42, 54),
- bg: Style::default(),
rosewater: Style::default().fg(cp(248, 248, 242)),
flamingo: Style::default().fg(cp(255, 121, 198)),
maroon: Style::default().fg(cp(255, 85, 85)),
@@ -777,7 +768,6 @@ impl Theme {
sapphire: Style::default().fg(cp(131, 165, 152)),
subtext1: Style::default().fg(cp(235, 219, 178)),
base: cp(40, 40, 40),
- bg: Style::default(),
rosewater: Style::default().fg(cp(235, 219, 178)),
flamingo: Style::default().fg(cp(211, 134, 155)),
maroon: Style::default().fg(cp(251, 73, 52)),
@@ -822,7 +812,6 @@ impl Theme {
sapphire: Style::default().fg(cp(156, 207, 216)),
subtext1: Style::default().fg(cp(224, 222, 244)),
base: cp(25, 23, 36),
- bg: Style::default(),
rosewater: Style::default().fg(cp(224, 222, 244)),
flamingo: Style::default().fg(cp(235, 188, 186)),
maroon: Style::default().fg(cp(235, 111, 146)),
@@ -839,6 +828,28 @@ impl Theme {
}
}
+impl Theme {
+ pub fn surface0_color(&self) -> Color {
+ self.surface0.fg.unwrap_or(self.base)
+ }
+
+ pub fn surface1_color(&self) -> Color {
+ self.surface1.fg.unwrap_or(self.base)
+ }
+
+ pub fn surface2_color(&self) -> Color {
+ self.surface2.fg.unwrap_or(self.base)
+ }
+
+ pub fn crust_color(&self) -> Color {
+ self.crust.fg.unwrap_or(self.base)
+ }
+
+ pub fn mantle_color(&self) -> Color {
+ self.mantle.fg.unwrap_or(self.base)
+ }
+}
+
fn cp(r: u8, g: u8, b: u8) -> Color {
Color::Rgb(r, g, b)
}
@@ -873,7 +884,8 @@ fn rgb_to_xterm256(red: u8, green: u8, blue: u8) -> u8 {
}
return 232 + ((u16::from(red) - 8) / 10) as u8;
}
- let nearest = |channel: u8| -> u16 {
+
+ let nearest_level = |channel: u8| -> u16 {
let channel = u16::from(channel);
let mut best_index = 0_u16;
let mut best_distance = u16::MAX;
@@ -886,7 +898,42 @@ fn rgb_to_xterm256(red: u8, green: u8, blue: u8) -> u8 {
}
best_index
};
- (16 + 36 * nearest(red) + 6 * nearest(green) + nearest(blue)) as u8
+ let ri = nearest_level(red);
+ let gi = nearest_level(green);
+ let bi = nearest_level(blue);
+ let cube_index = (16 + 36 * ri + 6 * gi + bi) as u8;
+ let cube_r = CUBE_LEVELS[ri as usize] as i32;
+ let cube_g = CUBE_LEVELS[gi as usize] as i32;
+ let cube_b = CUBE_LEVELS[bi as usize] as i32;
+ let cube_dist = (i32::from(red) - cube_r).pow(2)
+ + (i32::from(green) - cube_g).pow(2)
+ + (i32::from(blue) - cube_b).pow(2);
+
+ let lum =
+ (0.2126 * f32::from(red) + 0.7152 * f32::from(green) + 0.0722 * f32::from(blue)) as u8;
+ let gray_index = if lum < 8 {
+ 16u8
+ } else if lum > 238 {
+ 231u8
+ } else {
+ 232 + (u16::from(lum).saturating_sub(8) / 10) as u8
+ };
+ let gray_v = if gray_index == 16 {
+ 0i32
+ } else if gray_index == 231 {
+ 255i32
+ } else {
+ i32::from(8 + (gray_index - 232) * 10)
+ };
+ let gray_dist = (i32::from(red) - gray_v).pow(2)
+ + (i32::from(green) - gray_v).pow(2)
+ + (i32::from(blue) - gray_v).pow(2);
+
+ if gray_dist <= cube_dist {
+ gray_index
+ } else {
+ cube_index
+ }
}
#[cfg(test)]
@@ -907,6 +954,20 @@ mod tests {
assert_eq!(rgb_to_xterm256(0, 0, 255), 21);
}
+ #[test]
+ fn dark_low_sat_routes_to_gray_ramp() {
+ assert_eq!(rgb_to_xterm256(30, 30, 46), 234);
+ assert_eq!(rgb_to_xterm256(46, 52, 64), 236);
+ assert_eq!(rgb_to_xterm256(40, 42, 54), 235);
+ assert_eq!(rgb_to_xterm256(56, 58, 74), 237);
+ assert_eq!(rgb_to_xterm256(73, 76, 94), 238);
+ assert_eq!(rgb_to_xterm256(20, 80, 20), 22);
+ assert_eq!(rgb_to_xterm256(137, 180, 250), 111);
+ assert_eq!(rgb_to_xterm256(0, 0, 0), 16);
+ assert_eq!(rgb_to_xterm256(128, 128, 128), 244);
+ assert_eq!(rgb_to_xterm256(255, 255, 255), 231);
+ }
+
#[test]
fn non_rgb_colors_pass_through() {
assert_eq!(to_indexed_256(Color::Red), Color::Red);
@@ -921,7 +982,7 @@ mod tests {
quantized.border,
quantized.text,
quantized.accent,
- quantized.bg,
+ quantized.title,
quantized.lavender,
] {
assert!(
@@ -951,7 +1012,7 @@ mod tests {
);
assert!(
quantized
- .bg
+ .accent
.fg
.map(|c| !matches!(c, Color::Rgb(..)))
.unwrap_or(true)
@@ -1026,10 +1087,25 @@ mod tests {
assert_eq!(classify_terminal("", "", ""), ColorSupport::Basic);
}
+ #[test]
+ fn vte_version_threshold_respects_truecolor_boundary() {
+ unsafe {
+ std::env::set_var("VTE_VERSION", "3599");
+ }
+ assert_ne!(classify_terminal("", "xterm", ""), ColorSupport::Truecolor);
+ unsafe {
+ std::env::set_var("VTE_VERSION", "3600");
+ }
+ assert_eq!(classify_terminal("", "xterm", ""), ColorSupport::Truecolor);
+ unsafe {
+ std::env::remove_var("VTE_VERSION");
+ }
+ }
+
#[test]
fn detect_from_matches_support_matrix() {
let quantized = Theme::detect_from(ColorSupport::Color256, false);
- for style in [quantized.border, quantized.accent, quantized.bg] {
+ for style in [quantized.border, quantized.accent, quantized.title] {
assert!(
style
.fg
diff --git a/src/tui/widgets/badge.rs b/src/tui/widgets/badge.rs
index c0aa00c..062461b 100644
--- a/src/tui/widgets/badge.rs
+++ b/src/tui/widgets/badge.rs
@@ -1,10 +1,10 @@
use ratatui::{
- style::{Color, Modifier, Style},
+ style::{Modifier, Style},
text::Span,
};
use crate::providers::models::ProviderKind;
-use crate::tui::theme::{Theme, theme_color};
+use crate::tui::theme::Theme;
pub fn resolution_label(resolution: i64) -> &'static str {
match resolution {
@@ -24,6 +24,7 @@ pub fn resolution_badge_spans<'a>(
theme: &'a Theme,
basic_terminal: bool,
modal_active: bool,
+ is_selected: bool,
) -> Vec<Span<'a>> {
if modal_active {
if basic_terminal {
@@ -53,8 +54,8 @@ pub fn resolution_badge_spans<'a>(
_ if resolution > 0 => " HD ",
_ => " SD ",
};
- let badge_bg = theme_color(theme.surface0, theme.base);
- let contrast_fg = theme_color(theme.muted, Color::DarkGray);
+ let badge_bg = theme.surface0_color();
+ let contrast_fg = theme.overlay1.fg.unwrap_or(theme.base);
return vec![
Span::styled(label, Style::default().bg(badge_bg).fg(contrast_fg)),
Span::raw(" "),
@@ -77,59 +78,75 @@ pub fn resolution_badge_spans<'a>(
let (badge_bg, contrast_fg, label) = match resolution {
-1 => (
- theme_color(theme.lavender, Color::Rgb(180, 190, 254)),
- if theme.is_light {
- Color::White
+ if is_selected {
+ theme.lavender.fg.unwrap_or(theme.base)
} else {
- theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ theme.surface1_color()
+ },
+ if is_selected {
+ theme.crust_color()
+ } else {
+ theme.lavender.fg.unwrap_or(theme.base)
},
" Multi ",
),
2160 | 4320 => (
- theme_color(theme.rating, Color::Rgb(249, 226, 175)),
- if theme.is_light {
- Color::White
+ if is_selected {
+ theme.rating.fg.unwrap_or(theme.base)
+ } else {
+ theme.surface1_color()
+ },
+ if is_selected {
+ theme.crust_color()
} else {
- theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ theme.rating.fg.unwrap_or(theme.base)
},
" 4K ",
),
1080 => (
- theme_color(theme.sapphire, Color::Rgb(116, 199, 236)),
- if theme.is_light {
- Color::White
+ if is_selected {
+ theme.sapphire.fg.unwrap_or(theme.base)
+ } else {
+ theme.surface1_color()
+ },
+ if is_selected {
+ theme.crust_color()
} else {
- theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ theme.sapphire.fg.unwrap_or(theme.base)
},
" 1080p ",
),
720 => (
- theme_color(theme.teal, Color::Rgb(148, 226, 213)),
- if theme.is_light {
- Color::White
+ if is_selected {
+ theme.teal.fg.unwrap_or(theme.base)
} else {
- theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ theme.surface1_color()
+ },
+ if is_selected {
+ theme.crust_color()
+ } else {
+ theme.teal.fg.unwrap_or(theme.base)
},
" 720p ",
),
480 | 540 | 576 => (
- theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
- theme_color(theme.text, Color::White),
+ theme.surface2_color(),
+ theme.text.fg.unwrap_or(theme.base),
" 480p ",
),
360 => (
- theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
- theme_color(theme.text, Color::White),
+ theme.surface2_color(),
+ theme.text.fg.unwrap_or(theme.base),
" 360p ",
),
_ if resolution > 0 => (
- theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
- theme_color(theme.text, Color::White),
+ theme.surface2_color(),
+ theme.text.fg.unwrap_or(theme.base),
" HD ",
),
_ => (
- theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
- theme_color(theme.text_dim, Color::Gray),
+ theme.surface2_color(),
+ theme.text_dim.fg.unwrap_or(theme.base),
" SD ",
),
};
@@ -387,32 +404,56 @@ mod tests {
#[test]
fn test_resolution_badge_spans() {
let theme = Theme::default();
- let spans_4k = resolution_badge_spans(2160, &theme, false, false);
+ let spans_4k = resolution_badge_spans(2160, &theme, false, false, false);
assert_eq!(spans_4k[0].content, " 4K ");
- let spans_1080 = resolution_badge_spans(1080, &theme, false, false);
+ let spans_1080 = resolution_badge_spans(1080, &theme, false, false, false);
assert_eq!(spans_1080[0].content, " 1080p ");
- let spans_720 = resolution_badge_spans(720, &theme, false, false);
+ let spans_720 = resolution_badge_spans(720, &theme, false, false, false);
assert_eq!(spans_720[0].content, " 720p ");
- let spans_sd = resolution_badge_spans(480, &theme, false, false);
+ let spans_sd = resolution_badge_spans(480, &theme, false, false, false);
assert_eq!(spans_sd[0].content, " 480p ");
- let spans_multi = resolution_badge_spans(-1, &theme, false, false);
+ let spans_multi = resolution_badge_spans(-1, &theme, false, false, false);
assert_eq!(spans_multi[0].content, " Multi ");
- let basic_4k = resolution_badge_spans(2160, &theme, true, false);
+ let basic_4k = resolution_badge_spans(2160, &theme, true, false, false);
assert_eq!(basic_4k[0].content.trim(), "[4K]");
- let basic_multi = resolution_badge_spans(-1, &theme, true, false);
+ let basic_multi = resolution_badge_spans(-1, &theme, true, false, false);
assert_eq!(basic_multi[0].content.trim(), "[Multi]");
- let muted_multi = resolution_badge_spans(-1, &theme, false, true);
- assert_eq!(muted_multi[0].style.fg, theme.muted.fg);
- let muted_basic = resolution_badge_spans(-1, &theme, true, true);
+ let muted_multi = resolution_badge_spans(-1, &theme, false, true, false);
+ assert_eq!(muted_multi[0].style.fg, theme.overlay1.fg);
+ let muted_basic = resolution_badge_spans(-1, &theme, true, true, false);
assert_eq!(muted_basic[0].style.fg, theme.muted.fg);
}
+ #[test]
+ fn test_all_themes_badge_readability() {
+ for theme_name in crate::tui::theme::AVAILABLE_THEMES {
+ let kind = crate::tui::theme::ThemeKind::parse(theme_name);
+ let theme = crate::tui::theme::Theme::from_kind(kind);
+ for res in [-1, 2160, 1080, 720, 480] {
+ let unselected = resolution_badge_spans(res, &theme, false, false, false);
+ let selected = resolution_badge_spans(res, &theme, false, false, true);
+ assert!(unselected[0].style.bg.is_some());
+ assert!(unselected[0].style.fg.is_some());
+ assert!(selected[0].style.bg.is_some());
+ assert!(selected[0].style.fg.is_some());
+ assert_ne!(
+ unselected[0].style.bg, unselected[0].style.fg,
+ "Theme {theme_name} res {res} has identical fg and bg!"
+ );
+ assert_ne!(
+ selected[0].style.bg, selected[0].style.fg,
+ "Theme {theme_name} selected res {res} has identical fg and bg!"
+ );
+ }
+ }
+ }
+
#[test]
fn test_resolution_label() {
assert_eq!(resolution_label(-1), "Multi");
diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs
index 99f2200..0017137 100644
--- a/src/tui/widgets/settings.rs
+++ b/src/tui/widgets/settings.rs
@@ -427,7 +427,7 @@ fn render_general_settings(frame: &mut Frame, area: Rect, state: &AppState, them
Span::styled(after, theme.text),
]
} else {
- let input_bg = theme.surface0.fg.unwrap_or(theme.base);
+ let input_bg = theme.surface0_color();
let input_style = Style::default()
.fg(theme
.text
@@ -606,7 +606,7 @@ fn render_appearance_settings(frame: &mut Frame, area: Rect, state: &AppState, t
}
fn render_storage_settings(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
- let row_rects = settings_row_rects_in_area(area, 4);
+ let row_rects = settings_row_rects_in_area(area, 5);
let has_active_popup = has_active_settings_popup(state);
if let Some(&row_area) = row_rects.first() {
@@ -646,6 +646,40 @@ fn render_storage_settings(frame: &mut Frame, area: Rect, state: &AppState, them
if let Some(&row_area) = row_rects.get(1) {
let is_selected = state.settings_selected_row == 1;
let is_active_selected = is_selected && !has_active_popup;
+ let glyph = if state.basic_terminal { ">" } else { "▸" };
+ let value_spans = vec![Span::styled(
+ format!("Clear {glyph}"),
+ if has_active_popup {
+ theme.muted
+ } else if state.basic_terminal {
+ if is_active_selected {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.text_dim
+ }
+ } else if is_active_selected {
+ theme.error.add_modifier(Modifier::BOLD)
+ } else {
+ theme.error
+ },
+ )];
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ has_active_popup,
+ label: "Clear Watch History",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(2) {
+ let is_selected = state.settings_selected_row == 2;
+ let is_active_selected = is_selected && !has_active_popup;
let value_spans = if state.is_checking_updates {
vec![Span::styled(
"Checking...",
@@ -690,8 +724,8 @@ fn render_storage_settings(frame: &mut Frame, area: Rect, state: &AppState, them
);
}
- if let Some(&row_area) = row_rects.get(2) {
- let is_selected = state.settings_selected_row == 2;
+ if let Some(&row_area) = row_rects.get(3) {
+ let is_selected = state.settings_selected_row == 3;
let is_active_selected = is_selected && !has_active_popup;
let glyph = if state.basic_terminal { "->" } else { "↗" };
let value_spans = vec![Span::styled(
@@ -723,8 +757,8 @@ fn render_storage_settings(frame: &mut Frame, area: Rect, state: &AppState, them
state.basic_terminal,
);
}
- if let Some(&row_area) = row_rects.get(3) {
- let is_selected = state.settings_selected_row == 3;
+ if let Some(&row_area) = row_rects.get(4) {
+ let is_selected = state.settings_selected_row == 4;
let is_active_selected = is_selected && !has_active_popup;
let glyph = if state.basic_terminal { "->" } else { "▸" };
let value_spans = vec![Span::styled(
diff --git a/tests/live_stream_verification.rs b/tests/live_stream_verification.rs
index 7e625a1..ff695d9 100644
--- a/tests/live_stream_verification.rs
+++ b/tests/live_stream_verification.rs
@@ -88,6 +88,68 @@ async fn test_live_series_resolutions_and_streams() {
);
}
+#[tokio::test]
+#[ignore = "live network test; run with cargo test --test live_stream_verification -- --ignored"]
+async fn test_live_multiple_seasons_and_episodes_return_distinct_streams() {
+ let client = MovieBoxClient::new();
+ client.init().await.expect("client init successful");
+
+ for (subject_id, series_title, test_cases) in [
+ (
+ "6207982430134357800",
+ "Breaking Bad",
+ vec![(1, 1), (1, 2), (2, 1), (2, 2)],
+ ),
+ (
+ "4585605580068379856",
+ "One Piece S1-S2",
+ vec![(1, 1), (1, 2), (2, 1), (2, 2)],
+ ),
+ ] {
+ println!("\n=== Verifying {} ({}) ===", series_title, subject_id);
+ let mut urls = Vec::new();
+
+ for (season, episode) in test_cases {
+ let releases = client
+ .episode_streams(subject_id, season, episode)
+ .await
+ .expect("fetch streams");
+ assert!(
+ !releases.is_empty(),
+ "expected streams for {} S{:02}E{:02}",
+ series_title,
+ season,
+ episode
+ );
+ let url = releases[0]
+ .direct_url()
+ .expect("must have direct url")
+ .to_string();
+ println!(
+ "{} S{:02}E{:02} -> filename: {}, url: {}",
+ series_title, season, episode, releases[0].filename, url
+ );
+ assert!(
+ releases[0]
+ .filename
+ .contains(&format!("S{:02}E{:02}", season, episode)),
+ "filename must match season and episode"
+ );
+ urls.push(((season, episode), url));
+ }
+
+ for i in 0..urls.len() {
+ for j in (i + 1)..urls.len() {
+ assert_ne!(
+ urls[i].1, urls[j].1,
+ "Streams for {} S{:02}E{:02} and S{:02}E{:02} must not be the same! Got identical URL: {}",
+ series_title, urls[i].0.0, urls[i].0.1, urls[j].0.0, urls[j].0.1, urls[i].1
+ );
+ }
+ }
+ }
+}
+
#[tokio::test]
#[ignore = "live network test; run with cargo test --test live_stream_verification -- --ignored"]
async fn test_inspect_live_mpd_manifest() {
@@ -467,7 +529,7 @@ async fn test_live_moviebox_captions_end_to_end() {
let sibling_ids = vec!["3264772588333157424".to_string()];
let captions = service
- .get_ext_captions("4179386086617137184", resource_id, &sibling_ids)
+ .get_ext_captions("4179386086617137184", resource_id, &sibling_ids, 0, 0)
.await
.expect("fetch captions");
assert!(
@@ -519,7 +581,7 @@ async fn test_live_moviebox_breaking_bad_series_captions_latency() {
let t0 = std::time::Instant::now();
let captions = service
- .get_ext_captions(subject_id, resource_id, &sibling_ids)
+ .get_ext_captions(subject_id, resource_id, &sibling_ids, 1, 1)
.await
.expect("fetch captions");
let elapsed = t0.elapsed();
diff --git a/tests/settings_hub.rs b/tests/settings_hub.rs
index 752bb1f..99ce275 100644
--- a/tests/settings_hub.rs
+++ b/tests/settings_hub.rs
@@ -412,10 +412,48 @@ async fn test_settings_hub_browser_open_row_activation() {
SettingsCategory::StorageInfo,
))
.await;
- app.state_mut().settings_selected_row = 2;
+ app.state_mut().settings_selected_row = 3;
app.handle_action(Action::SettingsActivateRow).await;
let notification = app.state().notifications.back();
assert!(notification.is_some());
let title = &notification.unwrap().title;
assert!(title == "GitHub" || title == "Browser Launch Failed");
}
+
+#[tokio::test]
+async fn test_settings_hub_clear_watch_history_activation() {
+ let mut app = App::new();
+ let item = moviebox_tui::history::WatchHistoryItem {
+ provider: "moviebox".to_string(),
+ subject_id: "test-subj-1".to_string(),
+ title: "Test Movie".to_string(),
+ cover_url: None,
+ stype: 1,
+ release_year: "2024".to_string(),
+ season: 0,
+ episode: 0,
+ progress_seconds: 120,
+ duration_seconds: Some(600),
+ completed: false,
+ timestamp: 1000,
+ };
+ app.state_mut().history.record_start(&item, 120);
+ assert!(!app.state().history.recent.is_empty());
+
+ app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::SelectSettingsCategory(
+ SettingsCategory::StorageInfo,
+ ))
+ .await;
+ app.state_mut().settings_selected_row = 1;
+ app.handle_action(Action::SettingsActivateRow).await;
+
+ assert!(app.state().history.recent.is_empty());
+ let notification = app
+ .state()
+ .notifications
+ .back()
+ .expect("notification emitted");
+ assert_eq!(notification.title, "History");
+ assert_eq!(notification.message, "Watch history cleared");
+}
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index 39ea8f8..94d4c86 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -68,7 +68,6 @@ async fn test_download_subtitle_popup_renders_in_app_draw() {
assert!(content.contains("Subtitles"));
assert!(content.contains("No subtitles"));
assert!(content.contains("English"));
- assert!(content.contains("Download"));
}
#[tokio::test]
@@ -1095,7 +1094,7 @@ async fn test_landing_deck_header_renders_without_star_or_bracket() {
.map(|c| c.symbol())
.collect();
- assert!(text.contains("Continue Watching"));
+ assert!(text.contains("Resume"));
assert!(text.contains("Favorites"));
assert!(!text.contains("★"));
assert!(!text.contains("- * Favorites"));