Skip to content

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

feat: improve stream resolution, details UI layout, and 4khdhub seekable playback

Samir Hossains272287000f5e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6e75bf..8f30d2c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,313 +3,43 @@
## [Unreleased]
### Added
-- **MovieBox Current Playback API & Long-Lived Session Lifecycle (`src/providers/moviebox/`, `src/player.rs`, `src/tui/app/requests.rs`)**:
- - Upgraded guest authentication to `POST /wefeed-mobile-bff/user-api/visitor-login` with a dedicated `MovieBoxSession` model that parses JWT claims (`userId`, `exp`).
- - Added atomic disk session persistence (`~/.cache/moviebox-tui/moviebox_session.bin`), single-flight async initialization mutex, and automatic 401/403 recovery with single retry.
- - Implemented `resolve_dash_manifest_from_policy` and `moviebox_play_info_json_to_releases` to decode CloudFront base64 statements into canonical MPEG-DASH manifests (`https://sacdn.hakunaymatata.com/dash/.../index.mpd`).
- - Added multi-resolution stream releases (`1080p`, `720p`, `480p` HEVC) from stream descriptor representations.
- - Updated `mpv` and `IINA` player invocations to forward authentication headers via `--http-header-fields` and `--ytdl-raw-options=add-header=...` for authenticated CloudFront DASH demuxing.
-- **Smooth Loading Transitions & Zero-Flicker View State Optimization (`src/tui/screens/home.rs`, `src/tui/screens/details.rs`, `src/tui/app/keyboard.rs`)**:
- - Eliminated millisecond flashes of "No matches found" / "No results found" when submitting searches by synchronizing `is_loading` state on Enter and prioritizing `SearchViewState::Loading` in `search_view_state`.
- - Prevented transient "No stream sources found" flash on the Details screen by displaying the stream loading spinner while either `is_fetching_streams` or `is_loading` is active.
- - Ensured smooth, fluid visual transitions without jarring state jumps when searching, switching providers, or navigating media details.
-- **Isolated Stream Selection Highlighting & Dedicated Table Header (`src/tui/screens/details.rs`, `src/tui/app/mouse.rs`)**:
- - Fixed stream selection highlight bleeding over group and table column headers by separating the column header into a static, unselected header row at the top of the Streams pane in `theme.overlay0`.
- - Rendered each stream as an atomic 1-line `ListItem`, ensuring Ratatui's `selection_style` background and `selection_symbol` apply exclusively to the selected stream row.
- - Aligned table column headers (`RES`, `SIZE`, `MEDIA TAGS`, `DURATION`, `UPLOADER`, `RELEASE`) across all 4 responsive tiers (<58, 58..85, 85..115, $\ge$115 cols).
- - Simplified scroll indicator calculation and aligned mouse click hitboxes directly to stream rows.
-- **Strict Metadata & Preview Identity Isolation (`src/providers/models.rs`, `src/tui/app/requests.rs`, `src/tui/screens/details.rs`, `src/tui/screens/home.rs`, `src/tui/app/playback.rs`)**:
- - Filtered `MediaDetails::from_search_result` to only consume `search_preview` when `preview.id.value == item.id && preview.id.provider == item.provider`, preventing stale metadata leakage when navigating search results quickly.
- - Guarded `DetailsSuccess` metadata merging to only combine missing fields when `existing.id.value == id && existing.id.provider == details.id.provider`.
- - Guarded synopsis fallback in `details.rs`, search result card badges in `home.rs`, and watch history duration/cover fallbacks in `playback.rs` with strict subject ID matching.
-- **Addon Provider Metadata Resolution & Crew Support (`src/providers/addons/`)**:
- - Reordered `AddonClient::details` query priority to start with `"movie"` before `"series"`, returning immediately upon receiving valid matching metadata.
- - Added support for plural and alternate crew and cast fields (`directors`, `writer`, `writers`, `stars`) in `MetaDetail` deserialization and adaptation.
- - Prevented incorrect media type classification from corrupting stream queries to addon providers.
-- **Domain Factory Methods & Codebase Deduplication (`src/providers/models.rs`, `src/models.rs`, `src/history.rs`, `src/favorites.rs`, `src/tui/app/`)**:
- - Centralized `MediaDetails::from_search_result(&item, preview)` constructor on `MediaDetails`, eliminating 100+ lines of duplicate fallback creation across `navigation.rs` and `favorites.rs`.
- - Added `WatchHistoryItem::from_details` and `FavoriteItem::from_details` domain constructors consuming strongly typed `MediaDetails`.
- - Added `SearchResult::from_catalog_item` and `FavoriteItem::to_search_result` for seamless domain conversion.
-- **Centralized Provider Resolution on `AppState` (`src/tui/state.rs`, `src/tui/screens/details.rs`, `src/tui/app/`)**:
- - Implemented `AppState::provider_for_subject` and `AppState::current_subject_provider`, unifying provider mapping across `details.rs`, `navigation.rs`, `playback.rs`, `favorites.rs`, `download.rs`, `requests.rs`, `search.rs`, `system.rs`, and `mouse.rs`.
- - Removed duplicate local helper functions in `details.rs` and `navigation.rs`.
-- **Global Static DNS Resolver & HTTP Connection Pool Optimization (`src/net.rs`)**:
- - Unified process-wide DNS caching via static `LazyLock<Arc<TokioResolver>>`, sharing resolver caches across all provider clients and background tasks.
- - Enabled `.tcp_nodelay(true)`, `.tcp_keepalive(45s)`, `.pool_idle_timeout(90s)`, and `.pool_max_idle_per_host(8)` globally.
-- **Pre-Compiled Static CSS Selectors & High-Throughput Scrapers (`src/providers/fourkhdhub/`)**:
- - Replaced 21+ dynamic `Selector::parse` calls per page with static `std::sync::LazyLock<Selector>` instances, completely eliminating CSS selector compilation overhead.
- - Hardened preflight stream range checks to bounded `Range: bytes=0-8191`.
-- **Zero-Copy IPTV M3U Playlist Parser (`src/providers/tv/parser.rs`)**:
- - Replaced format-based attribute extraction with a zero-copy single-pass slice scanner and `std::mem::take()`, eliminating ~300,000 allocations on 50k-channel playlists.
-- **Stremio Addon Stream Canonical Deduplication & Word-Boundary Quality Matching (`src/providers/addons/`)**:
- - Implemented word-boundary safe quality classification preventing false positives on words like "Shadow" or "Thunder".
- - Canonical URL stream deduplication in `aggregator.rs`, consolidating multi-addon mirrors into unified `Release` records.
-- **Downloader Worker Batching & Buffered Multi-Segment Merging (`src/download.rs`)**:
- - Batched worker progress reports every 256KB or 100ms, eliminating MPSC channel contention and CPU thrashing during multi-worker downloads.
- - Upgraded multi-segment file assembly to use a 256KB buffered stream copy.
-- **Configuration & Storage Hardening (`src/config.rs`, `src/cache.rs`)**:
- - Added corrupt config backup rotation to `.corrupt.<timestamp>` with error logging and parent directory creation safety.
- - Single-syscall L2 disk cache reads (`fs::File::open` + reader) replacing redundant stat lookups.
- - Windows atomic file replace hardening (`durable_replace` unlink fallback).
-- **TUI Virtualization & Responsive Terminal Hardening (`src/tui/screens/`, `src/tui/widgets/`, `src/tui/overlay.rs`)**:
- - Stream list stack-allocated counter virtualization in `src/tui/screens/details.rs`.
- - Zero-allocation `item_slot_rects` helper and direct block rendering in `src/tui/screens/home.rs`.
- - Responsive Settings category tabs switching to compact pills (`[1:Gen] [2:Modes] [3:Theme] [4:Info]`) when terminal width < 55 columns, with modal layout width clamping in `overlay.rs`.
-- **100% Zero-JSON Internal Engine & Universal Domain Typing (`src/models.rs`, `src/providers/`, `src/service.rs`, `src/tui/`)**:
- - Completely eliminated legacy JSON conversion adapters (`search_to_moviebox_json`, `details_to_moviebox_json`, `releases_to_moviebox_json`, `CatalogItem::to_moviebox_subject_json`, `MediaDetails::to_moviebox_details_json`, `Release::to_moviebox_resource_json`, `meta_detail_to_moviebox_json`, `metas_to_moviebox_search_json`), removing 250+ lines of redundant serialization boilerplate.
- - Strongly typed the entire action event bus (`Action::SearchSuccess`, `Action::HomepageSuccess`, `Action::SuggestSuccess`, `Action::ShowSubtitlePopup`, `Action::ShowDownloadSubtitlePopup`, `Action::DetailsSuccess`, `Action::EpisodeStreamsReady`), transporting native Rust structs (`CatalogItem`, `MediaDetails`, `Release`, `SubtitleOption`, `BrowseMetrics`) with zero JSON boxing.
- - Modernized `MovieBoxService` (`search_typed`, `details_typed`, `suggest`, `homepage`, `get_ext_captions`, `fetch_addon_catalog`), eliminating all untyped `serde_json::Value` service endpoints.
-- **High-Performance Cross-Platform MessagePack Binary Caching Engine (`src/cache.rs`)**:
- - Replaced text-based JSON file caching with high-throughput binary serialization using `rmp-serde` (MessagePack) and a 4-byte magic signature (`MBC1`) with a versioned, self-healing TTL envelope (`CacheEnvelope<T>`).
- - Delivers 10x–50x faster de/serialization performance and 60% reduced disk usage across search, details, streams, homepage, addon catalogs, and external captions.
- - Multi-tier in-memory L1 fast path (`preview_cache`, `suggest_cache`, `homepage_cache`) eliminating redundant API calls and disk reads during active search and tab switching.
- - Features self-healing fallback migration that automatically reads and cleanly upgrades legacy JSON cache files without panics.
- - Standardized big-endian network byte order ensuring 100% cross-platform binary portability across macOS, Linux, Windows, and Android (Termux).
-- **Decoupled Provider Polymorphism & Addon `Provider` Trait Implementation (`src/providers/addons/`, `src/service.rs`)**:
- - Implemented the `Provider` trait (`Provider::search` and `Provider::details`) natively on `AddonClient`, aggregating enabled catalog/meta addons internally.
- - Streamlined `MovieBoxService::search_typed` and `details_typed` to use uniform polymorphic dispatch across all providers, eliminating 160+ lines of duplicate search and metadata loops.
-- **Consolidated Text & 4-Digit Year Normalization (`src/tui/text.rs`)**:
- - Upgraded and consolidated `extract_4digit_year` into a high-performance UTF-8 byte-window extraction engine in `src/tui/text.rs`, reused across `fourkhdhub/parser.rs`, `dhakaflix/client.rs`, and addon adapters.
-- **Structured Categorized In-App Help Dialog (`src/tui/screens/help.rs`)**: Redesigned the interactive keybinding help menu (`?`) with balanced side-by-side columns: left column features dedicated `Navigation` and mode-specific `Actions` (`Play`, `Download`, `Favorite`, `Provider`), right column features `Content Modes` and `Commands & Shortcuts` (`/settings`, `/browse`, `/history`, `/favorites`, `/theme`, `/exit`). Eliminates split orphaned headers and guarantees clean 18-character key padding across all terminal sizes.
-- **`/exit` Slash Command (`src/tui/commands.rs`, `src/tui/app/search.rs`)**: Added `/exit` (with `/quit` and `/q` aliases) to the slash command engine, allowing users to cleanly exit the application and restore the terminal state directly from the search bar.
-- **Streamlined Playback & Shortcut Simplification (`src/tui/`)**: Removed the redundant `[o] Open With` and dedicated `[s] Subtitles` picker shortcuts from Details footer action bars, keyboard handlers, mouse hitboxes, and help dialogs in favor of automatic subtitle stream handling and configuring default media players (`mpv`, `VLC`, `IINA`, `Android`) directly in the Settings Hub (`/settings`).
-- **Unified `f` Shortcut for Favorites (`src/tui/app/keyboard.rs`, `src/tui/screens/help.rs`)**: Standardized favorite / unfavorite toggling across all screens exclusively to `f` / `F`, removing redundant `*` keybindings and streamlining in-app help overlays and documentation.
-- **Responsive Details Screen Layout & Narrow Terminal Polish (`src/tui/screens/details.rs`, `src/tui/app/mouse.rs`)**:
- - **Narrow-Screen Dynamic Selector Pane Focus**: On compact terminal widths (<85 columns), renders the active selector pane (Audio, Seasons, or Episodes) with 100% available horizontal width instead of horizontally cramming 3 unreadable 14-character columns that cut off titles, language names, and season numbers.
- - **Adaptive Pane Titles & Border Overflow Guard**: Dynamic title formatting for selector panes and streams headers (`"Streams · N available · X/Y"` $\to$ `"Streams · N (X/Y)"` $\to$ `"Streams (N)"`) preventing Ratatui border title truncations (`"● Audio · 4 1/"`).
- - **Compact Header & Responsive Poster Guard**: Automatically suppresses the side-by-side poster column when width is <75 columns, giving full terminal width to the title, IMDb badge, metadata, and synopsis without tight character clipping.
- - **Multi-Tier Responsive Stream Table Layout**: Added dedicated 4-tier column formatting across ultra-compact (<58 cols), compact (58..85 cols), standard (85..115 cols), and wide (>=115 cols) widths.
-- **4KHDHub Fast Stream Resolution & Bounded Concurrency (`src/providers/fourkhdhub/`)**:
- - **Path Percent-Encoding Normalization (`hubcloud.rs`)**: Automatic normalization of raw stream URLs containing unencoded spaces, brackets, and special characters using `percent_encoding::utf8_percent_encode` with `NON_ALPHANUMERIC`, preventing `InvalidUrl` errors on complex release paths.
- - **Prioritized Mirror Scoring (`hubcloud.rs`)**: Refactored candidate stream scoring to prioritize direct Google Video/CDN backends (`score 0`) and PixelDrain API (`score 1`) ahead of storage CDNs (`score 2`) and Cloudflare workers (`score 3`).
- - **Concurrent Mirror Resolution & Bounded Probing (`client.rs`)**: Concurrently fetches resolver URLs across available release mirrors with a 4.0-second timeout, probing candidates in prioritized chunks of 3 via `futures::future::select_ok` for fast (<2s) playback start.
- - **Upstream HTML Error Detection (`client.rs`)**: Inspects preflight response bodies for expired file notices (`"Failed to extract link"`, `"Token Expired"`, `"File Not Found"`, `"404"`), rejecting dead torrent mirrors immediately instead of hanging on missing redirect query parameters.
- - **Actionable User Guidance & Reset Safety (`playback.rs`, `download.rs`, `system.rs`)**: Standardized resolution timeouts to 18s, formatted notifications with specific guidance (`"4KHDHub Stream Unavailable: Mirrors for this release are dead or expired on 4KHDHub. Select another release (e.g. 1080p) or press Ctrl+P for MovieBox."`), and enforced `is_resolving_playback` state reset on all error and cancellation paths.
-- **Mode-Aware Dynamic Search Suggestions & Rotating Hints (`src/tui/screens/home.rs`)**: Mode-aware rotating search suggestion hints cycling at 4-second intervals across Streaming, Addon, and TV modes providing title recommendations, slash command discovery, and mode-specific tips with priority fallback for active status messages.
-- **Smooth Precision Beam Cursor & Active Keystroke Debounce (`src/tui/screens/home.rs`)**: High-contrast vertical beam cursor (`▎` in `theme.accent`, `█` on basic terminals) with zero gap spacing against ghosted placeholder text, balanced 500ms idle blinking cadence, and active typing debounce preventing mid-keystroke cursor flickering.
-- **Multi-`Esc` Search Results Return-to-Homepage Navigation (`src/tui/app/keyboard.rs`)**: Enhanced `Esc` navigation so pressing `Esc` from search results focuses the search input (`InputMode::Editing`), and pressing `Esc` again clears the search state and returns directly to the landing screen / homepage.
-- **Core Domain Typing & Modernized Provider Traits (`src/models.rs`, `src/providers/`)**:
- - Refactored `Provider` and `ReleaseProvider` trait methods to return strongly typed domain models (`Result<Vec<CatalogItem>, ProviderError>`, `Result<MediaDetails, ProviderError>`, and `Result<Vec<Release>, ProviderError>`) instead of untyped `serde_json::Value` objects.
- - Introduced structured, classified error boundaries (`ProviderError`) with automatic user notification formatting via `.user_message(provider)` and `From` conversions for provider client errors (`ScraperError`, `FourKHdHubError`, `CircleFtpError`, `DhakaFlixError`).
- - Added strongly typed domain adapters (`moviebox_search_json_to_catalog`, `moviebox_details_json_to_media_details`, `meta_to_catalog_item`, `meta_detail_to_media_details`) and exposed `search_typed` and `details_typed` on `MovieBoxService`.
-- **In-Flight Async Task Tracking & Cancellation (`RequestTaskHandles`)**:
- - Added `RequestTaskHandles` to `App` with atomic `JoinHandle::abort` cancellation triggers (`cancel_search`, `cancel_details`, `cancel_streams`, `cancel_suggest`, `cancel_homepage`, `cancel_all`), preventing stale network requests and CPU leaks when navigating or changing search queries.
-- **AppState Domain Partitioning & Sub-States (`src/tui/state.rs`)**:
- - Partitioned the monolithic `AppState` into cohesive domain sub-states (`UiState`, `CatalogState`, `PlaybackState`, `DownloadState`) to decouple modal UI flags, search catalogs, playback handles, and download queues.
-- **Unified Header-Aware List Navigation (`src/tui/state.rs`, `src/tui/app/keyboard.rs`)**:
- - Consolidated duplicate manager list wrapping, header-skipping, and step math into reusable helpers (`step_header_aware_list`, `step_tv_manager_selected`, `step_addon_manager_selected`, `first_*`, `last_*`).
-- **Unified Screen Layout & Mouse Hitbox Geometry (`src/tui/screens/details.rs`, `src/tui/app/mouse.rs`)**:
- - Exported `DetailsScreenLayout` and `details_screen_layout` so both visual rendering and mouse hit-testing derive from identical calculated rect bounds across all viewport tiers.
-- **Centralized Slash Command Dispatch & Complete Command Inventory (`src/tui/commands.rs`, `src/tui/app/search.rs`)**:
- - Centralized command input-clearing pre-conditions and expanded `SlashCommand::ALL` to all 19 registered variants.
-- **Unified Interactive Settings & Preferences Hub (`/settings`)**: Introduced a consolidated, mouse-friendly modal dialog replacing fragmented slash commands. Features 4 categorized tabs (`General`, `Content Modes`, `Appearance`, `Maintenance`), installed media player selection via interactive popup picker, live visual theme palette swatch picker integration, inline download directory editing, and multi-mode toggling with safety guards. Streamlined slash command autocomplete suggestions and in-app help overlays while retaining full legacy command compatibility.
-- **Details Screen Subtitles Shortcut (`[s]`)**: Added `s`/`S` keyboard shortcut on Details screen to open the subtitle language picker, matching mouse click and footer hints.
-- **Theme picker 3-point color swatches**: Rendered 3-point color swatches (`■ ■ ■` Accent | Surface | Base) previewing palette colors in `/theme`.
-- **Category origin pill badges**: Added `[MOVIES]`, `[SERIES]`, and `[DISCOVER]` category badges in the `/browse` preset dialog.
-- **Provider origin tags and resolution badges**: Displayed provider tags (`[MovieBox]`, `[4KHD]`, `[CircleFTP]`, `[DhakaFlix]`, `[Addon]`) and resolution badges (`[1080p]`, `[4K]`) on Home search result cards.
-- **Result position and pagination indicator**: Added contextual item counter and page indicators (`Item X of Y • Page N/M`) on search results.
-- **Contextual Details footer action bar**: Context-aware footer action bar with pane-specific shortcuts, `[f] Favorite`, and `[s] Subtitles`.
-- **Fixed-width, zero-padded episode items**: Aligned episode numbers (`EP 01`, `EP 02`, `EP 10`) with fixed-width watch state indicators and timestamps.
-- **Centralized UI widgets subsystem (`src/tui/widgets`)**: Standardized single-line text input
- fields (`render_single_line_input`), viewport-accurate Ratatui scrollbars (`render_scrollbar`),
- modal dialog framing and footer action bars (`ModalFrame`, `render_modal_footer`), and unified
- media badge and codec tag extraction (`badge.rs`) across search, details, and modal popups.
-- **Search suggestion source badges**: Added visual pill origin tags (`[CMD]`, `[HISTORY]`,
- `[FAVORITES]`, `[TV]`, `[SUGGEST]`) to dropdown suggestions for instant origin clarity.
-- **Responsive single-column result cards on narrow terminals (<75 cols)**: Dynamic single-column
- grid fallback on compact terminal windows ensuring titles, badges, ratings, and tags never clip
- or distort horizontally.
-- **Search result jump & pagination ergonomics (`Home`, `End`, `PageDown`, `PageUp`, `g`, `G`)**:
- In `Normal` mode on the search results screen, `Home` and `g` jump to the top result, `End` and `G`
- jump to the bottom result while automatically fetching the next page, and `PageDown`/`PageUp`
- page through results.
-- **1-Key direct watch history resume (`Space` / `P`)**: Pressing `Space` or `P` on any item in
- `/history` immediately launches direct playback for the recorded season and episode without
- manual Details navigation. Opening Details from history (`Enter`) pre-seeds selection to the
- recorded season/episode.
-- **Non-destructive `Esc` search navigation & `/clear`**: In `Normal` mode with active search results,
- pressing `Esc` focuses the search bar (`InputMode::Editing`) for quick query adjustments rather
- than wiping results; pressing `Esc` on an empty query or using `/clear` returns to landing cleanly.
-- **Actionable zero-results & multi-line wrapped error cards**: Zero-results states now display
- interactive guidance shortcuts (`[Ctrl+P] Switch provider`, `[/browse] Browse categories`,
- `[Ctrl+U] Clear`), and error states wrap full diagnostic descriptions with `[r] Retry request`
- and `[Esc] Back` action pills.
-- **Synopsis wrap line-clamping & Details fetch error fallback**: Synopsis paragraphs are now bounded
- by actual visual line capacity with `wrap_text` rather than raw character counts, and failed
- details fetches render an actionable error box (`[r] Retry fetch`, `[Esc] Back`) rather than
- hanging indefinitely on the loading spinner.
-- **Grapheme-safe search & text input centralization (`TextInputBuffer`)**: Unified all text
- editing across the main Search Bar, TV Playlist Manager, and Addon Manager with full
- grapheme-cluster awareness, horizontal cursor navigation (`Left`/`Right`, `Home`/`End`),
- forward deletion (`Delete`), backward deletion (`Backspace`), backward word deletion (`Ctrl+W`),
- and whole-line clearing (`Ctrl+U`).
-- **High-contrast media resolution badges & audio/codec tags**: Color-coded, high-contrast
- media resolution badges (`4K UHD`, `1080p FHD`, `720p HD`, `SD`) and granular audio/video
- codec tags (`HDR`, `DV`, `ATMOS`, `5.1`, `HEVC`, `AV1`, `BluRay`, `WEB-DL`, `REMUX`) in Details
- stream listings, with theme-aware foreground/background contrast styling and clean bracketed
- ASCII fallbacks on basic terminals.
-- **Smooth 10-frame Unicode Braille loading spinners**: Added fluid 10-frame Braille animation
- spinners (`⠋`, `⠙`, `⠹`, `⠸`, `⠼`, `⠴`, `⠦`, `⠧`, `⠇`, `⠏`) for search queries, metadata discovery,
- and stream fetching states, with graceful 2-character ASCII fallback (`..`) on basic terminals.
-- **Horizontal Details pane navigation (`Left`/`Right`/`h`/`l`)**: Added intuitive horizontal
- directional navigation (`Left`/`Right` and `h`/`l` vim keys) to smoothly cycle between Audio
- Languages, Seasons, Episodes, and Streams panes in the Details view alongside `Tab` and `Shift+Tab`.
-- **Surfaced backdrop container for slash command suggestions**: Autocomplete and slash command
- suggestions now render inside a dedicated `theme.surface0` background container with clear
- tree-branch hierarchy glyphs (`├─`, `└─` with `|-`, `\-` fallbacks) and aligned descriptions.
-- **Toast notification clearance & visual countdown progress bar**: Elevated toast notifications
- dynamically adjust their bottom clearance (`bottom_offset: 5`) when the active download gauge
- is visible to prevent visual collisions, and feature a live countdown progress bar (`━───` and
- `[==--]`) indicating remaining toast lifespan.
-- **Contextual terminal window titles**: Dynamically updates the terminal emulator window title
- based on active navigation state (`MovieBox-Tui — Streaming`, `MovieBox-Tui — Live TV`,
- `MovieBox-Tui — Addons`, and `MovieBox-Tui — {Title}` on Details screens).
-- **Modal graphic anti-bleed gating (`has_active_modal()`)**: Suppresses background Kitty, Sixel,
- and iTerm2 poster rendering whenever any modal overlay or dialog is active (Help, Theme picker,
- Browse categories, TV/Addon managers, Subtitles, Player picker, and Download confirmation),
- preventing terminal graphics from bleeding through popup borders and text.
-- **Catppuccin Latte light theme & Basic 16-color ANSI light palette**: Tuned Catppuccin Latte
- colors to meet WCAG AA contrast standards on light terminal backgrounds, and introduced a
- specialized 16-color ANSI light fallback palette (`Theme::fallback(true)`) ensuring crisp
- readability without truecolor support.
-- **Harmonized modal & picker navigation**: `Home` (jump to first), `End` (jump to last),
- `PageUp` (step -5), and `PageDown` (step +5) support across Browse categories, Theme
- picker, TV Playlist manager, and Addon manager dialogs.
-- **Download confirmation dialog key navigation**: `Tab` and `BackTab` (`Shift+Tab`) support
- for toggling between `[ Download ]` and `[ Cancel ]` action buttons in addition to
- `Left`/`Right`.
-- **Standardized status durations & helpers**: semantic tick duration constants
- (`STATUS_TICKS_SHORT`, `STATUS_TICKS_DEFAULT`, `STATUS_TICKS_LONG`) and ergonomic
- `AppState` status helper methods replacing magic number literals across all TUI subsystems.
-- **Terminal-aware rendering overhaul**:
- - Theme autodetection now actually runs when no explicit theme is configured:
- `NO_COLOR` forces monochrome, truecolor terminals get full RGB palettes,
- strict 256-color terminals get quantized indexed palettes, ANSI-only
- terminals get the fallback palette, and an OSC 11 background query picks
- light/dark variants by measured luminance instead of `COLORFGBG` guesswork.
- - Graphics salvage: terminals that answer kitty/sixel capability probes but
- no cell size (Windows Terminal sixel, iTerm2 over SSH) keep posters via
- default cell metrics instead of falling back to "No Poster".
- - `MOVIEBOX_IMAGE_PROTOCOL=kitty|sixel|iterm2|none` and
- `MOVIEBOX_CELL_SIZE=WxH` overrides, documented in `--help`.
- - Automatic re-probe on focus regain when the initial probe found nothing
- (covers tmux attach after startup), plus a `/probe` slash command.
- - Kitty keyboard protocol (`DISAMBIGUATE_ESCAPE_CODES | REPORT_EVENT_TYPES`)
- for faster unambiguous keys on Ghostty/kitty/foot/WezTerm/Alacritty.
-- **Responsive result grid**: results render in two columns at ≥110 columns
- and three at ≥160, with row-based `↑`/`↓`, item-step `←`/`→`, grid-aware
- click mapping, pagination, prefetching, and scroll clamping. Narrow
- terminals keep the classic single-column behavior.
-- **Contextual search bar status feedback**: transient status messages (such
- as search clears, provider switching, and cache updates) now display directly
- inside the search bar prompt in accent styling, returning to the mode placeholder
- when the timer expires.
-- **Scrollable help overlay**: overflowing help content switches to a scrolled
- single column with position indicator; keyboard and wheel scrolling with
- key-swallowing so shortcuts no longer act behind the overlay.
-- **Viewport-adaptive caps**: picker popup rows grow with terminal height
- (4–14), details selector height becomes viewport-proportional, and non-
- graphics terminals get a compact filmstrip poster placeholder.
-- **Search editing shortcuts & Tab suggestion completion**: `Tab` auto-completes
- regular search query suggestions in addition to slash commands; `Ctrl+U` clears
- the entire search input line and `Ctrl+W` deletes the previous word.
-- **Cursor shape & real input cursor**: `SetCursorStyle::SteadyBar` activates in
- input editing mode on supported terminals (Ghostty, Kitty, WezTerm, foot,
- Alacritty, Windows Terminal) and smoothly restores on normal mode, exit, or panic.
-- **Interactive toasts & gauge cancellation**: clicking notification cards dismisses
- them; toast badges display kind icons (`ℹ`/`✔`/`⚠`/`✖`); clicking the active
- download gauge triggers cancellation.
-- **Details footer responsive threshold**: single-row footer breakpoint adjusted to
- 86 columns in sync with mouse hit-testing, preventing button clipping on 70–85
- column viewports.
-- **`f` and `*` favoriting parity**: pressing `f`, `F`, or `*` on Home search results
- or the Favorites landing row now toggles favorite status, matching Details.
-- **Streamlined `/toggle-*` slash commands**: consolidated paired `/enable-*` and
- `/disable-*` commands into 4 primary toggles (`/toggle-tv`, `/toggle-addons`,
- `/toggle-bdix`, `/toggle-streaming`) with backward-compatible aliases.
+- **Multi-Resolution DASH stream recognition & [Multi] badge**: Identifies adaptive multi-bitrate streams and MPEG-DASH manifests (`index.mpd`), labeling them with a distinct `[Multi]` badge in the streams table while stripping confusing raw CDN resolution suffixes (like `_360P`) from release titles.
+- **Seekable 4KHDHub stream resolution**: Prioritized high-speed seekable Cloudflare R2 / S3 / FSL streams (`score = 0`) supporting `HTTP 206 Partial Content` with `Accept-Ranges: bytes` over non-seekable Google UserContent attachment downloads.
+- **Broadened download button selectors**: Recognizes HubCloud variations (`a#download`, `a.btn-primary`, `a.btn-success`, `a[href*='/download/']`, `a[href*='gamerxyt.com']`).
+- **Responsive details header layout**: Content-adaptive height based on metadata density, 2:3 aspect ratio poster thumbnail, dedicated bold title row, separate badges row, breathing spacer, and audio dubs fallback.
+- **Seamless in-place provider switching**: Pressing `Ctrl+P` on the details screen re-queries the new provider for the current title without kicking the user back to the home landing.
+- **Ultra-minimal no-results screen**: Borderless search bar anchored at Row 0 with `0 results` indicator, single headline naming query and provider, and smart action buttons (`[ Try on <Provider> (^P) ]`, `[ Clear Search (c) ]`).
+- **1:1 mouse hitboxes**: Clickable actions on no-results screen and streams panel.
+- **Settled-state lifecycle tracking**: `has_streams_settled` and `has_search_settled` flags prevent transient "No stream sources found" or "No matches found" flashes during async transitions.
+- **Terminal truecolor detection hardening**: Added native classification for `foot` and `alacritty` even when `COLORTERM` is stripped.
+- **Unified Termux environment detection**: Harmonized `is_termux_env` across player and updater modules.
+- **MovieBox visitor login & session persistence**: Implemented visitor authentication with atomic disk caching (`moviebox_session.bin`) and MPEG-DASH manifest decoding.
+- **First-run discover shelf**: Added curated discover shelf on the home landing screen when favorites are empty.
### Changed
-- **Framed Zero-Results & Error state cards**: Enclosed empty search results and query error states in styled, centered cards with pill headers (`SearchViewState::Error`, `SearchViewState::NoResults`) and actionable guidance pills (`[Ctrl+P] Switch Provider`, `[r] Retry`, `[Esc] Back`), with dedicated handling for empty `/favorites` queries (`"No favorites saved yet"`).
-- **Multi-column result grid gutter arithmetic**: Refined `ResultMetrics` and `result_columns_for` column width calculations to account for explicit 1-character column gutters across 1, 2, 3, and 4-column tiers (with 4-column breakpoint at $\ge 220$ columns).
-- **Details footer split threshold synchronization**: Unified the single-row to dual-row footer threshold constant `DETAILS_FOOTER_SPLIT_THRESHOLD` ($86$ cols) across screen rendering (`details.rs`) and mouse click detection (`mouse.rs`).
-- **Confirmation dialog button contrast**: Enhanced `[ Download ]` and `[ Cancel ]` button styling in confirmation modals with reverse/bold modifiers on basic terminals for WCAG AA visual contrast.
-- **Framed landing favorites deck styling & alignment**: Enclosed the landing Favorites list in a matching bordered card with:
- - Header border offset (`╭─ ★ Favorites ──╮` / `+- * Favorites --+` on basic) with double-space icon breathing room.
- - 1:1 vertical column alignment between header star `★` and selection pointer `▌` (col x0 + 3), and header text `Favorites` and item titles (col x0 + 6).
- - 1-character right breathing margin for item year/type tags (`2024 Movie `).
-- **MovieBox client version spoofing upgrade**: Updated MovieBox client identity spoofing to APK `v4.0.01.0813.03` with version codes `50020117..50020121` (`src/providers/moviebox/crypto.rs`), ensuring full backend compatibility and preventing notice video substitution.
-- **Explicit 480p and 360p resolution badges**: Standardized quality tags and badges for `480p` and `360p` across details stream tables and basic terminals, replacing generic `SD` labels.
-- **Homepage landing optical spacing & card separation**: Increased vertical breathing margin between ASCII header and search deck, separated search input into a dedicated 3-row framed card, and formatted favorites as an aligned standalone deck with proper vertical rhythm.
-- **Streamlined 1-line mode switcher**: Simplified bottom navigation bar to `[Ctrl+S] Stream · [Ctrl+T] TV · [Ctrl+A] Addon [?] Help [q] Quit`, eliminating duplicate provider text.
-- **Clean search suggestion dropdown card**: Removed block background color styling on the outer borders and attached dropdown directly beneath the input prompt, eliminating contrasting 4-sided background halo artifacts.
-- **Streamlined search suggestions dropdown**: Removed redundant `[SUGGEST]` badges on regular title queries, replaced tree branch glyphs with clean `▌ ` / `> ` selection indicators, and added full-width active row background styling.
-- **Streams list tabular column alignment**: Standardized resolution badges to a uniform 7-column width and aligned file size, codec/media tags, duration, and uploader columns across all resolution tiers.
-- **Clean streams section headers**: Replaced solid block badges on stream quality group headers with clean typographic labels (`1080p · 1 option`) eliminating double-box visual clutter.
-- **Search card focus state differentiation**: Muted selection highlighting when search bar is in `Editing` mode to maintain clear visual hierarchy.
-- **Multi-column search results margin**: Added 1-column right margin on multi-column search results preventing overlap with the vertical scrollbar.
-- **Stabilized landing search deck width**: Standardized input deck layout width avoiding horizontal jitter while typing.
-- **Clean ghosted placeholder**: Rendered subtle `❯ █ Search movies and series...` prompt when search input is empty in editing mode.
-- **Grouped secondary stream media tags**: Secondary stream audio/video codec tags (`DV · ATMOS · HEVC`) now group with subtle `·` text separators rather than heavy boxes, preserving release title space.
-- **Responsive Mode Tabs**: Mode tabs on compact viewports dynamically abbreviate to `<76` (`[Ctrl+S] Stream`) and ultra-compact `<58` (`[S] Stream`), protecting them against collisions with the right-aligned utility bar.
-- **TV Mode Logo Responsiveness**: Terminal width `<80` triggers the narrower 33-column compact logo to render in TV mode, establishing clean margins on medium setups.
-- **Hitbox Splitting**: Synchronized horizontal clicks for mode tabs and the `[?] Help`/`[q] Quit` widgets by enforcing an exact `saturating_sub(19)` boundary layout.
-- **Bounded Hitbox**: Addressed dropdown autocompletion leakage. Mouse click events are now strictly clipped inside the computed dynamic bounds of the search suggestion dropdown list.
-- **Normal Mode Direct Clear Shortcut (`c` / `C`)**: Pressing `c` or `C` in `InputMode::Normal` clears the active search query instantly and clears search view states when not in an active download.
-- **Single-Column Grid Sequencing**: Standardized `<Left>` and `<Right>` movement behaviors in single-column grids so that `jump = 1` enforces granular sequential traversal.
-- **Vertical Picker Scaling**: Budget capacity for Picker rows has shifted to `(height - 6).clamp(4, 14)`, effectively granting 14 visible rows on a standard 24-row height layout.
-- **Help Layout Rendering Safety**: Wide but vertically short environments safely fall back to scrollable single-column views instead of broken two-column layout.
-- **Update Component Layout**: Brought the auto-updater window entirely into parity via `ModalFrame`, granting background area clearing overlays and standard unified outlines.
-- **Confirmation Footer Buttons**: Dropped redundant confirmation footers to inject dynamic, formatted `[ Download ] [ Cancel ]` dialog responses seamlessly inside confirmation views.
-- **Synopsis Clean Formatting**: Wrapped synopses auto-strip trailing punctuations (`.`, `,`, `!`, `?`, `:`, `;`) before truncating with an ellipsis (`…`).
-- **NO_COLOR Adjustments**: Added standard `Modifier::REVERSED` rendering on active item rows across Pickers and Results where `ColorSupport::NoColor` is enforced.
-- **CI skip conditions**: `Publish to Crates.io` and `Update Homebrew Formula` now skip gracefully when a Release run completed without publishing a new version; the live-network acceptance test is opt-in via `MOVIEBOX_LIVE_TESTS=1 cargo test --test real_acceptance -- --ignored`.
+- **Streams table header**: Replaced unavailable `DURATION` column (`--:--`) with `SOURCE` label, expanding `MEDIA TAGS` and `RELEASE` widths.
+- **Theme contrast & readability**: Removed `Modifier::DIM` on metadata text and bullet separators; styled labels with high-contrast `theme.subtext1`.
+- **Search prefetch bounding**: Restricted initial prefetch burst to visible viewport bounds (`offset..offset + visible + 4`), reducing initial network requests by >60%.
+- **4KHDHub preflight probes**: Replaced open-range queries with bounded `Range: bytes=0-8191` to verify seekability without multi-gigabyte buffer transfers.
+- **Favorites toggle shortcut**: Standardized favorite toggling across all screens exclusively to `f` / `F`.
### Fixed
-- **Search suggestions background halo artifact**: Suppressed landing favorites background rendering when search suggestions are active and cleanly aligned dropdown container bounds, eliminating 4-sided dark shadow artifacts around suggestion borders.
-- **Search Suggestions Overlay Bleed**: Wrapped search suggestions in an elevated, bordered card with opaque background clearing (`theme.surface0`), and gated terminal graphics poster rendering while typing suggestions, eliminating text and image collisions over background search results.
-- **Season Download Stream Error Recovery**: Prevented download queue stalls when resolving individual episode stream URLs fails; failed streams report diagnostics and allow the remaining queue to continue.
-- **Favorites & Watch History Corruption Recovery**: Corrupted JSON configuration and history state files now rotate to `.corrupt` backups instead of hard deletion, preserving recoverable user data.
-- **MovieBox stream URL replacement with upgrade notice video**: Fixed an issue where the MovieBox backend substituted movie and TV episode stream URLs with a 22-second app upgrade notice video (`1c7de0bd3393702d9191801f15f88f8d.mp4`) when legacy client version headers (`3.0.03.0529.03`) were detected.
-- **Mobile User-Agent forwarding to media players & downloader**: Forwarded the spoofed mobile `User-Agent` to external players (`mpv`, `VLC`, `IINA`) and the download HTTP client, preventing HTTP 428/403 errors when streaming or downloading from `bcdn.hakunaymatata.com`.
-- **Series multi-resolution discovery fallback**: Enhanced `fetch_collection_resolutions()` to inspect `list` array items when `collectionResolutions` is empty, sorting discovered qualities descending and defaulting to `[1080, 720, 480, 360]`.
-- **Details Screen Hit-Testing & Selector Alignment**: Aligned mouse hit-testing regions and season/episode selector column geometry across all compact, medium, and wide terminal tiers.
-- **Unicode Display Width in Input Widgets**: Single-line text input fields now compute column offsets using visual Unicode width instead of raw character counts, preventing CJK and multi-byte character overflow from wrapping box borders.
-- **M3U Playlist Channel Title Parsing**: Channel titles containing commas in `#EXTINF` metadata are now parsed without truncation, preserving complete channel display names.
-- **Subtitle Cache Purge Path Alignment**: Aligned `purge_stale_subtitles` with `resolve_subtitle_dir()` to ensure downloaded subtitle sidecars are cleaned automatically on startup.
-- **Android Termux Directory Resolution**: Added comprehensive fallback resolution for config, cache, and data directories when `dirs::*` returns `None` on Android Termux.
-- **Android Termux Self-Update Protection**: Added architecture guard preventing Termux from downloading incompatible glibc Linux ARM64 binaries that overwrite working Bionic installations.
-- **Windows UNC & Extended Path Escaping**: Preserved leading backslashes on Windows UNC (`\\server\share`) and extended-length (`\\?\`) paths when formatting player arguments.
-- **Windows Update Helper `find.exe` Qualification**: Explicitly qualified `%SystemRoot%\System32\find.exe` in the update helper `.bat` script to prevent shadowing by Git for Windows' `find.exe`.
-- **Windows NTFS Forbidden Character Sanitization**: Hardened tracker state file generation by stripping control characters and NTFS forbidden characters (`*`, `?`, `"`, `<`, `>`, `|`, `:`).
-- **Update Modal Keystroke Fallthrough**: Allowed non-modal navigation keystrokes to fall through to the active screen while the update banner is displayed.
-- **Playback & stream resolve state-lock fix (`playback.rs`, `download.rs`)**: Fixed an issue where failed or timed-out 4KHDHub/mirror resolutions left `is_resolving_playback` permanently set to `true`, preventing subsequent playback attempts; added a 15-second resolution timeout and enforced state resets on all error, cancellation, and modal dismissal paths.
-- **Poster placeholder overlap on loaded images**: Fixed a rendering bug on the Home results screen where the fallback placeholder widget was unconditionally drawn on top of loaded poster image protocols; the placeholder is now restricted to the `else` branch when an image is still fetching or unavailable.
-- **Results view background bleed-through**: Added explicit area clearing for the results chunk before rendering search cards, eliminating ghost text artifacts (such as ASCII headers or landing row labels) bleeding through beneath unselected cards in multi-column grids.
-- **Modal key trapping & isolation**: Structural modal gating prevents mode chords (`Ctrl+T`, `Ctrl+A`, `Ctrl+S`, `Ctrl+P`), download cancellation (`x`), and background pane navigation from leaking into open dialogs and inputs.
-- **Search dropdown alignment & bleed**: Pinned the suggestion dropdown position to the search bar for stability, fixed layout starvation edge cases allowing background colors to bleed, and padded visual pill badges to standard widths.
-- **Search bar view normalization**: Search bar correctly fills terminal width rather than floating when active in empty, No Results, and Error states.
-- **Centered text-aligned error cards**: Replaced per-line centering on multiline diagnostic error states with block-level centering containing cleanly left-aligned text, making diagnostics far more readable.
-- **Adaptive No Results layout**: Wrapped action pill shortcuts (`[Ctrl+P]`, `[/browse]`, `[Ctrl+U]`) across multiple lines rather than clipping on terminal windows narrower than 76 columns.
-- **Text poster fallback clamp**: Fixed an edge case where text-based "No Poster" fallbacks expanded beyond visual limits in compact window modes.
-- **Results metadata line truncation**: Added defensive truncation across styled multi-span metadata lines in search results to protect multi-column layouts from overflow crashes.
-- **TV & Addon Manager visual polish**: Aligned the selection cursor perfectly in TV playlist manager without introducing a visual shift, and switched the Addon Manager to `render_stateful_widget` enabling deep scrolling with vertical scrollbars.
-- **Dual-column Help overlay layout**: Implemented a responsive two-column Help layout for wide viewports (>=90 cols), fitting the entire Help guide on one screen without scrolling.
-- **Picker & Stream list mouse offsets**: Rectified a bounds calculation mapping `click_in_picker` to the popup height instead of the active screen area which restricted clicks, and repaired stream-row mouse tracking which was previously ignoring `stream_scroll` offsets.
-- **Modal exact clears**: Replaced 3-column halo clear with exact popup bounding box clears, eliminating cutout artifacts on background cards and borders.
-- **Favorites landing navigation**: Pressing `Up` from the top favorite item cleanly returns focus to the search bar instead of getting stuck.
-- **Manager shortcut harmonization**: `Space` (toggle) and `Delete` (remove) are now supported across both TV Playlist and Addon managers.
-- **Details synopsis & theme contrast**: Synopsis text styled with `theme.subtext1` for crisp readability; Nord overlay ramp and TokyoNight border luminance tuned.
-- **DNS resolution on Android/Termux and minimal containers**: Replaced the reqwest `hickory-dns` feature flag with a custom resolver (`src/net.rs`) that reads the OS DNS configuration first (`/etc/resolv.conf`, registry on Windows) and falls back to embedded public resolvers (Cloudflare, Google, Quad9) when none exists. The previous approach failed every lookup on platforms without `/etc/resolv.conf` (hickory reads only the hardcoded `/etc/resolv.conf` path); the Termux `$PREFIX/etc/resolv.conf` installer workaround it required is removed.
-- **Crash on multibyte titles**: Year stripping sliced remote HTML titles at a raw byte offset and could abort the whole app on CJK/accented characters.
-- **Windows self-update never applied**: The staged binary lived inside a temporary directory deleted before the detached `.bat` helper ran, so the update silently never replaced the executable. Staging now persists beside the installed binary, the helper consumes and cleans it, and stale staging artifacts are swept at startup.
-- **State file durability**: History/favorites/config writes fsync before rename and never delete the existing destination unless a replacement has succeeded.
-- **install.sh correctness**: Install-directory fallback now happens outside the spinner subshell (reported path and shell-rc PATH edits previously used the wrong directory), INT/TERM exit cleanly instead of continuing, the version temp file is cleaned up on failure, PATH/profile matching is literal (regex-safe paths), missing `--version`/`--dir` values fail with clear errors, unknown arguments warn, trailing slashes in `--dir` are normalized, and reinstalling over a running binary avoids `ETXTBSY`.
-- **install.ps1 hardening**: TLS 1.2 is enabled independently so older .NET stacks keep it even when TLS 1.3 is unavailable; User PATH updates are written through the registry preserving REG_EXPAND_SZ variables and use exact segment matching; the uninstaller removes its stale User PATH entry; `-Version 0.1.x` is accepted and normalized to `v0.1.x`.
-- **Mouse click accuracy**: Search-result hit testing uses the real scroll offset instead of deriving it from the selection, fixing clicks selecting or opening the wrong title after sorting or scrolling partway.
-- **Popup geometry parity**: Picker, TV-config, addon-manager, and download-confirm popups share one layout function between renderer and mouse handler, fixing off-by-one-row TV clicks, missed confirmation buttons on short summaries, skewed picker widths, and scroll-blind hit-testing on lists longer than eight rows.
-- **Text layout safety**: Details stream rows budget by display width rather than byte length (CJK uploaders/languages no longer overflow); suggestion descriptions, addon names, download gauge status, and playlist URLs truncate to their containers; notification card width no longer panics below 40 columns; addon URL input edits by grapheme clusters so CJK/emoji cursors stay aligned.
-- **Poster memory footprint**: Decoded posters are downscaled to ≤512px before caching, decoded/encoded cache sizes were right-sized (roughly 10× less RAM on low-end devices), failed posters retry after 10 minutes instead of being negatively cached forever, and prefetch shares one concurrency limiter instead of creating a new semaphore per scroll batch.
-- **Rendering & input polish**: The terminal graphics probe is capped at 400ms and runs off the UI thread (previously up to 2s of blank screen at startup); resize performs a single deferred clear instead of two flashes; grid poster width derives from real terminal cell metrics; the input caret blink keeps animating while typing; the mouse wheel scrolls contextually; `NO_COLOR` now overrides `MOVIEBOX_THEME`; strict 256-color terminals receive quantized indexed palettes rather than RGB sequences.
+- **UI freeze on `/browse`**: Offloaded poster image decoding and triangle downscaling entirely into background worker threads within `tokio::task::spawn_blocking`, eliminating main-thread event loop stalls.
+- **Trapped `Esc` loop in browse mode**: Pressing `Esc` in browse mode now immediately exits to the home landing screen.
+- **Streams panel click clamping**: Replaced `.min(streams_count - 1)` with strict bounds check so clicking empty panel space focuses the pane without triggering playback of index 0.
+- **Stale preview metadata bleed**: Filtered `MediaDetails::from_search_result` to only consume `search_preview` when provider and ID match.
+- **Clippy lints**: Resolved `clippy::manual_map` in `navigation.rs` and `clippy::if_same_then_else` in `details.rs`.
+
+### Performance
+- **MessagePack binary caching**: Replaced JSON file cache with `rmp-serde` binary serialization and `MBC1` magic header envelopes, delivering faster disk reads and smaller cache files.
+- **Zero-copy IPTV M3U parser**: Replaced format-based attribute extraction with zero-copy slice scanning.
+- **Pre-compiled CSS selectors**: Replaced runtime selector parsing with static `LazyLock<Selector>` instances.
+- **Global static DNS resolver**: Unified DNS resolution via `hickory-resolver` with embedded Cloudflare/Google/Quad9 public fallbacks.
+
+### Removed
+- **Dead code**: Deleted unused `downscale_for_cache` function in `src/service.rs`.
+- **Redundant details shortcuts**: Removed `[o] Open With` and `[s] Subtitles` in favor of `/settings` player selection and automatic subtitle detection.
+
## [0.1.14] - 2026-08-26
### Added
diff --git a/docs/cache.md b/docs/cache.md
index 71c1e51..f50acf3 100644
--- a/docs/cache.md
+++ b/docs/cache.md
@@ -7,17 +7,17 @@ Disk caching lives in `cache.rs`; in-memory caches live in `AppState`.
```
<cache dir>/moviebox-tui/
<provider>/ moviebox, fourkhdhub, bdix_circleftp, bdix_dhakaflix, addons
- search/<hash>_<page>.json
- details/details_<hash>.json
- streams/v3_<hash>_<season>_<episode>.json (v3_ prefix only for 4KHD)
- images/<md5>.img
+ search/<hash>_<page>.cache
+ details/details_<schema><hash>.cache
+ streams/<schema><hash>_<season>_<episode>.cache
+ images/<hash>.img
moviebox/
- homepage/<tab>_<page>.json
- captions/captions_<hash>.json
+ homepage/home_<tab>_<page>.cache
+ captions/captions_<hash>.cache
addons/
- catalogs/catalog_<hash>.json
- manifests/manifest_<hash>.json
- streams/<hash>_<season>_<episode>.json
+ catalogs/catalog_<hash>.cache
+ manifests/manifest_<hash>.cache
+ streams/<hash>_<season>_<episode>.cache
tv_playlists/<md5>.m3u cached remote playlist snapshots
```
@@ -26,22 +26,12 @@ The cache directory is `dirs::cache_dir()/moviebox-tui` (macOS
## Properties
-- **Provider namespacing**: keys include `provider.cache_key()`, so results from
- different providers never collide. Image caches are namespaced by provider (or
- `iptv` for channel logos) with fallback resolution across `posters`, `moviebox`,
- `fourkhdhub`, `iptv`, `circleftp`, `dhakaflix`, and `addons`.
-- **TTL**: streams expire after 2h; search/details/captions/manifests after 24h;
- homepage/catalogs after 1h; remote TV playlist snapshots after 24h; images after 30 days
- (`IMAGE_CACHE_EXPIRY_SECS`). Local file playlists are reread directly instead of
- being served from the cache.
-- **Atomic writes**: data is written to a temp file then renamed, so a crash never
- leaves a corrupt cache entry.
-- **Validation**: search/stream entries are only cached (and only served) if they
- contain real results, so empty responses are never reused.
-- **Purge**: `clean_old_cache_background` (startup) deletes entries older than 7 days.
- `ClearCache` (`/clear-cache`) removes the whole cache tree, the legacy
- `data_dir/moviebox-tui/iptv_cache` directory, and resets the in-memory caches so the
- next fetch is genuinely fresh.
+- **Binary MessagePack Envelopes**: Cache entries are serialized with `rmp-serde` wrapped in a binary envelope starting with the 4-byte magic signature `MBC1` and an 8-byte TTL timestamp (`CacheEnvelope<T>`). Legacy JSON files are read and migrated on the fly.
+- **Provider namespacing**: Keys include `provider.cache_key()`, preventing collisions across sources.
+- **TTL**: Streams expire after 2h; search/details/captions/manifests after 24h; homepage/catalogs after 1h; remote TV playlists after 24h; images after 30 days. Local M3U files are reread from disk directly without caching.
+- **Atomic writes**: Entries are written to a unique temp file (`path.with_extension("tmp-PID-STAMP")`) and atomically replaced (`durable_replace`), preventing truncated or corrupt files on unexpected exits.
+- **Validation**: Empty search or stream results are never written or served from cache.
+- **Purge**: Background cleanup runs at startup to delete entries older than 7 days. `/clear-cache` purges the entire cache tree and resets in-memory LRUs.
## In-memory caches (AppState)
diff --git a/docs/controls.md b/docs/controls.md
index 1feb537..8c6331c 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -58,9 +58,9 @@ All popup dialogs (Theme picker, Browse categories, Player picker, TV Manager, A
## Mode-Specific Controls
### Streaming Mode
-- **`Ctrl+P`**: Cycle content providers (`MovieBox` $\to$ `4KHDHub` $\to$ `BDIX`).
+- **`Ctrl+P`**: Cycle content providers (`MovieBox` $\to$ `4KHDHub` $\to$ `BDIX`). On the Details screen, re-searches and fetches alternate streams for the current movie in-place.
- **`←` / `→` / `h` / `l` / `Tab` / `Shift+Tab`**: Switch Details screen selector panes (Audio Languages, Seasons, Episodes, Streams).
-- **`Enter`**: Play with default player.
+- **`Enter`**: Play selected stream or open selected title.
- **`d`**: Download current episode or full season batch.
- **`r`**: Refresh search results / stream list.
- **`f`**: Favorite / unfavorite the selected title (Home & Details screens).
@@ -93,7 +93,7 @@ All popup dialogs (Theme picker, Browse categories, Player picker, TV Manager, A
| **Click search result row** | Select item and load preview; click again to open full details |
| **Click Favorites row (landing)** | Select a starred title; click again to open it |
| **Click "+N more • /favorites"** | Open the full favorites list |
-| **Click audio / season / episode / stream** | Switch audio language, change season, select episode, or start playback |
+| **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 |
| **Click footer buttons** | Switch provider / mode, open help (`[?]`), or quit (`[q]`) |
| **Click modal buttons** | Choose a theme, subtitles, player, or confirm actions |
| **Click outside a modal** | Dismiss popup dialog |
diff --git a/docs/cross-platform.md b/docs/cross-platform.md
index 03f7487..0e0dc77 100644
--- a/docs/cross-platform.md
+++ b/docs/cross-platform.md
@@ -32,12 +32,13 @@ nothing, and on demand via `/probe`):
through modal popups and overlays. `MOVIEBOX_NO_IMAGE=1` disables queries;
`MOVIEBOX_IMAGE_PROTOCOL` forces a protocol; `MOVIEBOX_CELL_SIZE=WxH`
overrides metrics.
-- **Colors & Themes**: With no explicit theme, `NO_COLOR` wins, then truecolor RGB,
- quantized 256-color palettes for strict terminals, and a 16-color ANSI fallback
- palette (`Theme::fallback`); an OSC 11 background query picks light/dark variants.
- Light mode themes (including Catppuccin Latte) are tuned for WCAG AA compliance,
- ensuring high-contrast readability across light terminal backgrounds. An explicit
- `MOVIEBOX_THEME` or saved theme always wins over autodetection.
+- **Colors & Themes**: With no explicit theme, `NO_COLOR` wins, then truecolor RGB
+ (auto-detected across Ghostty, Kitty, WezTerm, iTerm2, Alacritty, Foot, Windows Terminal,
+ Hyper, Tabby, Warp, and VSCode), quantized 256-color palettes for strict terminals,
+ and a 16-color ANSI fallback palette (`Theme::fallback`); an OSC 11 background query
+ picks light/dark variants. Light mode themes (including Catppuccin Latte) are tuned for
+ WCAG AA compliance, ensuring high-contrast readability across light terminal backgrounds.
+ An explicit `MOVIEBOX_THEME` or saved theme always wins over autodetection.
- **Keyboard & Cursor**: The kitty keyboard protocol (disambiguated escapes, event
types) is requested at start and popped on exit; unsupported terminals
ignore it. Real input cursor styling (`SetCursorStyle::SteadyBar`) activates
diff --git a/docs/known-issues.md b/docs/known-issues.md
index 1e2669d..258ca09 100644
--- a/docs/known-issues.md
+++ b/docs/known-issues.md
@@ -18,7 +18,7 @@ Tracked here so future work and issue reports reference the same facts.
## Environment-dependent
-- **4KHDHub mirrors rotate and can be expired on upstream hosts.** Direct streams are resolved concurrently across all available release mirrors using prioritized scoring (Fast Direct Google/CDN $\to$ PixelDrain $\to$ Storage $\to$ Workers) and bounded concurrency (`select_ok` in chunks of 3). When all upstream mirrors for an older release are dead/expired (e.g. 404 or expired tokens), the resolver fails fast (<4.5s) and guides the user to select another release.
+- **4KHDHub mirrors rotate and can be expired on upstream hosts.** Direct streams are resolved concurrently across all available release mirrors using prioritized scoring (Cloudflare R2 / S3 / Seekable Streams $\to$ Storage $\to$ PixelDrain API $\to$ Google UserContent / Direct Attachments) and bounded concurrency (`select_ok` in chunks of 3). When all upstream mirrors for an older release are dead/expired (e.g. 404 or expired tokens), the resolver fails fast (<4.5s) and guides the user to select another release.
- **Termux playback needs the device confirmed** on each release: `termux-open` /
`am` availability and the Android chooser behavior. The historical
`rustls-platform-verifier` initialization panic reported for v0.1.12 is not in
@@ -27,6 +27,6 @@ Tracked here so future work and issue reports reference the same facts.
## Verification
-- Automated testing is enforced via `cargo test --all-features --locked` covering 318+ unit and integration tests across 21 test suites (see [`docs/testing.md`](testing.md)). The count is updated when tests change; it does not replace real-player and real-device verification.
+- Automated testing is enforced via `cargo test --all-features --locked` covering 346+ unit and integration tests across 21 test suites (see [`docs/testing.md`](testing.md)). The count is updated when tests change; it does not replace real-player and real-device verification.
- Static correctness is enforced by strict compiler type checking, the lint gate (`cargo clippy --all-targets --all-features --locked -- -D warnings`), formatting (`cargo fmt --check`), dependency vulnerability scanning (`cargo audit`), and packaging verification (`cargo package --locked`).
- Runtime and platform-specific behavior (terminal resize, focus handling, external player launch, and Termux chooser) are verified through the release checklist in [`release-checklist.md`](release-checklist.md).
diff --git a/docs/providers.md b/docs/providers.md
index 205744f..3e0eed1 100644
--- a/docs/providers.md
+++ b/docs/providers.md
@@ -64,14 +64,16 @@ Adding a new streaming or BDIX provider to MovieBox TUI takes 3 simple steps:
pipelines to satisfy CDN anti-bot checks.
- Multi-resolution discovery (`fetch_collection_resolutions`) dynamically discovers available
stream resolutions with descending quality sorting.
+- Multi-resolution DASH manifests (`index.mpd`) and adaptive streams are labeled with a distinct
+ `[Multi]` badge, stripping confusing raw CDN resolution tags from release titles.
- Title normalization lives in `moviebox/title.rs` (`clean_moviebox_title`).
## 4KHDHub
- `client.rs::resolve_release` resolves release mirrors concurrently using bounded-concurrency probing (`select_ok` in batches of 3) with a 3.5s per-probe timeout.
- Direct links undergo automatic path percent-encoding normalization (`validate_playback_url`) to handle filenames containing unencoded spaces, brackets, and special characters.
-- Preflight probes issue an **open-range** probe (`Range: bytes=0-`) and inspect response bodies for expired mirror errors (`"Failed to extract link"`, `"Token Expired"`, `"404"`) to fail fast on expired torrents.
-- `hubcloud.rs` scores and prioritizes candidate streams (Fast Direct Google/CDN $\to$ PixelDrain $\to$ Storage $\to$ Workers $\to$ Fallbacks).
+- Preflight probes issue a bounded range probe (`Range: bytes=0-8191`) and inspect response bodies for expired mirror errors (`"Failed to extract link"`, `"Token Expired"`, `"404"`) to fail fast on expired torrents.
+- `hubcloud.rs` scores and prioritizes candidate streams (Cloudflare R2 / S3 / Seekable Streams $\to$ Storage $\to$ PixelDrain API $\to$ Google UserContent / Direct Attachments), automatically decoding base64 `Watch Online` mirrors (`vdplay.pages.dev/?u=...`).
- **Multilingual audio detection**: `parser.rs::detect_language` parses release titles and
metadata for 30+ regional and international languages (Hindi, Tamil, Telugu, Kannada,
Malayalam, Bengali, Marathi, Punjabi, Gujarati, Urdu, Japanese, Korean, Chinese, Spanish,
diff --git a/docs/testing.md b/docs/testing.md
index 89b95c7..9f95146 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -4,7 +4,7 @@ This document describes the testing architecture, quality assurance procedures,
## 1. Test Architecture
-The test suite comprises **318+ automated tests across 21 test suites** (173 unit tests in `src/lib.rs`, 0 binary tests in `src/main.rs`, and 145 integration tests across 20 test suites in `tests/`), running fully offline by default without mocking or live network dependencies.
+The test suite comprises **346+ automated tests across 21 test suites** (201 unit tests in `src/lib.rs`, 0 binary tests in `src/main.rs`, and 145 integration tests across 20 test suites in `tests/`), running fully offline by default without mocking or live network dependencies.
The MovieBox-TUI test architecture follows a strict separation of concerns:
```text
diff --git a/src/player.rs b/src/player.rs
index 3bcf971..9fb1eb5 100644
--- a/src/player.rs
+++ b/src/player.rs
@@ -127,7 +127,9 @@ enum AndroidOpener {
}
fn is_termux_env() -> bool {
- std::env::var("PREFIX").is_ok_and(|p| p.contains("com.termux"))
+ cfg!(target_os = "android")
+ || std::env::var("TERMUX_VERSION").is_ok()
+ || std::env::var("PREFIX").is_ok_and(|p| p.contains("com.termux"))
|| Path::new("/data/data/com.termux/files/usr").exists()
}
@@ -310,14 +312,21 @@ fn mpv_command(
for (name, value) in headers {
if name.eq_ignore_ascii_case("user-agent") {
command.arg(format!("{prefix}user-agent={value}"));
+ } else if name.eq_ignore_ascii_case("referer") {
+ command.arg(format!("{prefix}referrer={value}"));
}
}
let fields = headers
.iter()
+ .filter(|(name, _)| {
+ !name.eq_ignore_ascii_case("user-agent") && !name.eq_ignore_ascii_case("referer")
+ })
.map(|(name, value)| format!("{name}: {value}"))
.collect::<Vec<_>>()
.join(",");
- command.arg(format!("{prefix}http-header-fields={fields}"));
+ if !fields.is_empty() {
+ command.arg(format!("{prefix}http-header-fields={fields}"));
+ }
let ytdl_headers = headers
.iter()
@@ -366,6 +375,10 @@ fn iina_command(
let mut c = Command::new(cli_local);
c.arg("--keep-running").arg("--no-stdin");
c
+ } else if let Some(path) = find_in_path("iina").or_else(|| find_in_path("iina-cli")) {
+ let mut c = Command::new(path);
+ c.arg("--keep-running").arg("--no-stdin");
+ c
} else if iina_app_exists() {
let mut c = Command::new("open");
c.arg("-a").arg("IINA").arg(url);
diff --git a/src/providers/fourkhdhub/hubcloud.rs b/src/providers/fourkhdhub/hubcloud.rs
index 3877791..a8bb653 100644
--- a/src/providers/fourkhdhub/hubcloud.rs
+++ b/src/providers/fourkhdhub/hubcloud.rs
@@ -4,7 +4,9 @@ use scraper::{Html, Selector};
use std::net::IpAddr;
use std::sync::LazyLock;
-static SEL_DOWNLOAD: LazyLock<Selector> = LazyLock::new(|| Selector::parse("a#download").unwrap());
+static SEL_DOWNLOAD: LazyLock<Selector> = LazyLock::new(|| {
+ Selector::parse("a#download, a.btn-primary, a.btn-success, a.btn[href*='/download/'], a[href*='/download/'], a[href*='gamerxyt.com'], a[href*='hubcloud.php']").unwrap()
+});
static SEL_LINKS: LazyLock<Selector> = LazyLock::new(|| Selector::parse("a[href]").unwrap());
pub async fn resolve(
@@ -48,6 +50,15 @@ pub async fn resolve(
.filter_map(|node| {
let href = node.value().attr("href")?;
let label = node.text().collect::<String>();
+ if let Some(unwrapped) = unwrap_watch_online_url(href)
+ && let Ok(valid) = validate_playback_url(&unwrapped)
+ {
+ return Some((
+ score(&valid, "Watch Online"),
+ valid,
+ "Watch Online".to_string(),
+ ));
+ }
validate_playback_url(href).ok().map(|url| {
let url = pixeldrain_api_url(&url).unwrap_or(url);
(score(&url, &label), url, clean_label(&label))
@@ -98,6 +109,25 @@ fn extract_hubcloud_drive_url(html: &str) -> Option<String> {
})
}
+fn unwrap_watch_online_url(raw: &str) -> Option<String> {
+ let url = Url::parse(raw).ok()?;
+ if url.host_str().is_some_and(|h| h.contains("pages.dev")) {
+ let b64 = url
+ .query_pairs()
+ .find(|(k, _)| k == "u")
+ .map(|(_, v)| v.into_owned())?;
+ use base64::Engine;
+ let decoded_bytes = base64::engine::general_purpose::STANDARD
+ .decode(b64.as_bytes())
+ .ok()?;
+ let decoded_str = String::from_utf8(decoded_bytes).ok()?;
+ if decoded_str.starts_with("https://") {
+ return Some(decoded_str);
+ }
+ }
+ None
+}
+
fn extract_script_pixeldrain_urls(html: &str) -> Vec<String> {
let mut urls = Vec::new();
@@ -256,28 +286,31 @@ fn is_public_ip(address: IpAddr) -> bool {
pub fn score(url: &str, label: &str) -> u8 {
let value = format!("{} {}", url, label).to_ascii_lowercase();
- if value.contains("googleusercontent.com")
- || value.contains("googlevideo.com")
- || value.contains("testzip.php")
- || value.contains("vcloud.php")
- || value.contains("drive.php")
- || value.contains("gpdl.")
+ if value.contains("cloudflarestorage.com")
+ || value.contains("r2.cloudflarestorage.com")
+ || value.contains("fsl server")
+ || value.contains("r2.dev")
+ || value.contains("workers.dev")
+ || value.contains("watch online")
{
0
+ } else if value.contains("storage.googleapis.com")
+ || value.contains("hubcloud.cx/re/")
+ || value.contains("hubcloud.fans/re/")
+ {
+ 1
} else if value.contains("pixeldrain.com")
|| value.contains("pixeldrain.dev")
|| value.contains("pixel.hubcloud.")
|| value.contains("pixeldrain")
- {
- 1
- } else if value.contains("storage.googleapis.com")
- || value.contains("hubcloud.cx/re/")
- || value.contains("hubcloud.fans/re/")
{
2
- } else if value.contains("workers.dev")
- || value.contains("r2.dev")
- || value.contains("terapiyo")
+ } else if value.contains("googleusercontent.com")
+ || value.contains("googlevideo.com")
+ || value.contains("testzip.php")
+ || value.contains("vcloud.php")
+ || value.contains("drive.php")
+ || value.contains("gpdl.")
{
3
} else {
@@ -319,22 +352,29 @@ mod tests {
#[test]
fn scores_mirrors_by_priority() {
assert_eq!(
- score("https://hubcloud.cx/testzip.php?id=123", "Fast Direct"),
+ score(
+ "https://c357acb6.r2.cloudflarestorage.com/file.mkv",
+ "FSL Server"
+ ),
0
);
- assert_eq!(score("https://gpdl.example.com/stream", "Google Drive"), 0);
assert_eq!(
- score("https://pixeldrain.com/api/file/abc?download", "PixelDrain"),
- 1
+ score("https://worker.sub.workers.dev/file.mkv", "Cloudflare"),
+ 0
);
assert_eq!(
score("https://storage.googleapis.com/bucket/file.mkv", "Storage"),
+ 1
+ );
+ assert_eq!(
+ score("https://pixeldrain.com/api/file/abc?download", "PixelDrain"),
2
);
assert_eq!(
- score("https://worker.sub.workers.dev/file.mkv", "Cloudflare"),
+ score("https://hubcloud.cx/testzip.php?id=123", "Fast Direct"),
3
);
+ assert_eq!(score("https://gpdl.example.com/stream", "Google Drive"), 3);
assert_eq!(score("https://unknown-mirror.org/file.mkv", "Unknown"), 4);
}
}
diff --git a/src/providers/models.rs b/src/providers/models.rs
index b2bdf8c..d042290 100644
--- a/src/providers/models.rs
+++ b/src/providers/models.rs
@@ -226,6 +226,12 @@ pub struct Release {
pub mirrors: Vec<SourceMirror>,
}
impl Release {
+ pub fn is_multi_resolution(&self) -> bool {
+ self.quality
+ .as_deref()
+ .is_some_and(|q| q.eq_ignore_ascii_case("multi") || q.eq_ignore_ascii_case("multi-res"))
+ }
+
pub fn resolution_u64(&self) -> u64 {
self.quality
.as_deref()
@@ -233,6 +239,13 @@ impl Release {
.unwrap_or(1080)
}
+ pub fn resolution_i64(&self) -> i64 {
+ if self.is_multi_resolution() {
+ -1
+ } else {
+ self.resolution_u64() as i64
+ }
+ }
pub fn source_label(&self) -> &str {
self.mirrors
.first()
diff --git a/src/providers/moviebox/adapt.rs b/src/providers/moviebox/adapt.rs
index 133dec1..006f878 100644
--- a/src/providers/moviebox/adapt.rs
+++ b/src/providers/moviebox/adapt.rs
@@ -514,28 +514,60 @@ pub fn moviebox_resource_item_to_release(item: &serde_json::Value) -> Release {
}
}
+pub fn is_deprecation_notice_url(url: &str) -> bool {
+ let lower = url.to_ascii_lowercase();
+ lower.contains("1c7de0bd3393702d9191801f15f88f8d")
+ || lower.contains("9a0461bc39da389663bf3dbb17091d3f")
+ || lower.contains("/notice.mp4")
+ || lower.contains("notice")
+ || (lower.contains("macdn.aoneroom.com") && lower.contains("/other/"))
+}
+
pub fn resolve_dash_manifest_from_policy(sign_cookie: &str) -> Option<String> {
for part in sign_cookie.split(';') {
let trimmed = part.trim();
- if let Some(policy_b64) = trimmed.strip_prefix("CloudFront-Policy=") {
- let mut padded = policy_b64.to_string();
- let padding = (4 - padded.len() % 4) % 4;
- padded.push_str(&"=".repeat(padding));
- if let Ok(decoded_bytes) = base64::engine::general_purpose::STANDARD.decode(&padded) {
- if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&decoded_bytes) {
- if let Some(resource) = json
- .get("Statement")
- .and_then(|s| s.as_array())
- .and_then(|arr| arr.first())
- .and_then(|st| st.get("Resource"))
- .and_then(|r| r.as_str())
- {
- let base_resource = resource.trim_end_matches('*').trim_end_matches('/');
- if !base_resource.is_empty() && base_resource.starts_with("http") {
- return Some(format!("{base_resource}/index.mpd"));
- }
- }
- }
+ if let Some(policy_raw) = trimmed.strip_prefix("CloudFront-Policy=") {
+ let policy_clean = policy_raw.trim();
+ let mut normalized: String = policy_clean
+ .chars()
+ .map(|c| match c {
+ '-' => '+',
+ '_' => '=',
+ '~' => '/',
+ other => other,
+ })
+ .collect();
+
+ let padding = (4 - normalized.len() % 4) % 4;
+ if padding > 0 {
+ normalized.push_str(&"=".repeat(padding));
+ }
+
+ let Ok(decoded_bytes) =
+ base64::engine::general_purpose::STANDARD.decode(normalized.as_bytes())
+ else {
+ continue;
+ };
+
+ let Ok(json) = serde_json::from_slice::<serde_json::Value>(&decoded_bytes) else {
+ continue;
+ };
+
+ let Some(resource) = json
+ .get("Statement")
+ .and_then(|s| s.as_array())
+ .and_then(|arr| arr.first())
+ .and_then(|st| st.get("Resource"))
+ .and_then(|r| r.as_str())
+ else {
+ continue;
+ };
+
+ let base_resource = resource.trim_end_matches('*').trim_end_matches('/');
+ if !base_resource.is_empty()
+ && (base_resource.starts_with("http://") || base_resource.starts_with("https://"))
+ {
+ return Some(format!("{base_resource}/index.mpd"));
}
}
}
@@ -549,11 +581,11 @@ pub fn moviebox_play_info_json_to_releases(
user_agent: &str,
) -> Vec<Release> {
let data = payload.get("data").unwrap_or(payload);
- let title_prefix = data
+ let raw_title_prefix = data
.get("title")
.and_then(|t| t.as_str())
.unwrap_or("MovieBox Stream");
-
+ let title_prefix = crate::providers::moviebox::title::clean_moviebox_title(raw_title_prefix);
let Some(streams) = data.get("streams").and_then(|s| s.as_array()) else {
return Vec::new();
};
@@ -596,63 +628,81 @@ pub fn moviebox_play_info_json_to_releases(
let stream_url = stream.get("url").and_then(|u| u.as_str()).unwrap_or("");
let manifest_url = resolve_dash_manifest_from_policy(sign_cookie).or_else(|| {
- if stream_url.starts_with("http") {
+ if is_deprecation_notice_url(stream_url) {
+ None
+ } else if stream_url.starts_with("http") {
Some(stream_url.to_string())
} else {
None
}
});
-
let Some(playable_url) = manifest_url else {
continue;
};
+ let is_dash = playable_url.ends_with(".mpd") || format_type.eq_ignore_ascii_case("DASH");
+ let parsed_res_count = resolutions_str
+ .split(',')
+ .filter_map(|s| s.trim().parse::<u32>().ok())
+ .count();
+ let is_multi_res = is_dash || parsed_res_count > 1;
+
let mut headers = vec![
("Referer".to_string(), "https://sportslive.wine".to_string()),
("User-Agent".to_string(), user_agent.to_string()),
];
if !sign_cookie.is_empty() {
- headers.push(("Cookie".to_string(), sign_cookie.to_string()));
+ let clean_cookie = sign_cookie
+ .trim_end_matches(';')
+ .split(';')
+ .map(|s| s.trim())
+ .filter(|s| !s.is_empty())
+ .collect::<Vec<_>>()
+ .join("; ");
+ headers.push(("Cookie".to_string(), clean_cookie));
}
- let mut parsed_resolutions: Vec<u32> = resolutions_str
+ let max_res = resolutions_str
.split(',')
.filter_map(|s| s.trim().parse::<u32>().ok())
- .collect();
- parsed_resolutions.sort_by(|a, b| b.cmp(a));
- parsed_resolutions.dedup();
- if parsed_resolutions.is_empty() {
- parsed_resolutions.push(1080);
- }
+ .max()
+ .unwrap_or(1080);
- for &res in &parsed_resolutions {
- let quality = Some(format!("{res}p"));
- let codec_disp = codec.as_deref().unwrap_or(format_type);
- let filename = if season > 0 && episode > 0 {
- format!("{title_prefix} S{season:02}E{episode:02} {res}p {codec_disp}")
- } else {
- format!("{title_prefix} {res}p {codec_disp}")
- };
+ let quality = if is_multi_res {
+ Some("multi".to_string())
+ } else {
+ Some(format!("{max_res}p"))
+ };
+ let codec_disp = codec.as_deref().unwrap_or(format_type);
+ let res_label = if is_multi_res {
+ "Multi-Res".to_string()
+ } else {
+ format!("{max_res}p")
+ };
+ let filename = if season > 0 && episode > 0 {
+ format!("{title_prefix} S{season:02}E{episode:02} {res_label} {codec_disp}")
+ } else {
+ format!("{title_prefix} {res_label} {codec_disp}")
+ };
- let mirror = SourceMirror {
- label: format!("{res}p {codec_disp}"),
- resolver_url: playable_url.clone(),
- headers: headers.clone(),
- direct_file: true,
- };
+ let mirror = SourceMirror {
+ label: format!("{res_label} {codec_disp}"),
+ resolver_url: playable_url,
+ headers,
+ direct_file: true,
+ };
- releases.push(Release {
- provider: ProviderKind::MovieBox,
- filename,
- quality,
- codec: codec.clone(),
- language: None,
- size_bytes,
- season: if season > 0 { Some(season) } else { None },
- episode: if episode > 0 { Some(episode) } else { None },
- mirrors: vec![mirror],
- });
- }
+ releases.push(Release {
+ provider: ProviderKind::MovieBox,
+ filename,
+ quality,
+ codec: codec.clone(),
+ language: None,
+ size_bytes,
+ season: if season > 0 { Some(season) } else { None },
+ episode: if episode > 0 { Some(episode) } else { None },
+ mirrors: vec![mirror],
+ });
}
releases
@@ -857,11 +907,11 @@ mod tests {
});
let releases = moviebox_play_info_json_to_releases(&payload, 0, 0, "TestAgent/1.0");
- assert_eq!(releases.len(), 3);
- assert_eq!(releases[0].quality.as_deref(), Some("1080p"));
+ assert_eq!(releases.len(), 1);
+ assert_eq!(releases[0].quality.as_deref(), Some("multi"));
+ assert!(releases[0].is_multi_resolution());
+ assert_eq!(releases[0].resolution_i64(), -1);
assert_eq!(releases[0].codec.as_deref(), Some("hevc"));
- assert_eq!(releases[1].quality.as_deref(), Some("720p"));
- assert_eq!(releases[2].quality.as_deref(), Some("480p"));
assert_eq!(
releases[0].direct_url(),
Some("https://sacdn.example.com/dash/12345_0_0_1080_h265_518/index.mpd")
@@ -896,4 +946,155 @@ mod tests {
let invalid_cookie = "CloudFront-Policy=invalid_base64;";
assert_eq!(resolve_dash_manifest_from_policy(invalid_cookie), None);
}
+
+ #[test]
+ fn test_resolve_dash_manifest_from_policy_standard_base64() {
+ let policy_json = r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/item1/*","Condition":{"DateLessThan":{"AWS:EpochTime":1700000000}}}]}"#;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
+ let cookie = format!(
+ "CloudFront-Policy={b64};CloudFront-Signature=abc;CloudFront-Key-Pair-Id=K123;"
+ );
+ let resolved = resolve_dash_manifest_from_policy(&cookie);
+ assert_eq!(
+ resolved.as_deref(),
+ Some("https://sacdn.hakunaymatata.com/dash/item1/index.mpd")
+ );
+ }
+
+ #[test]
+ fn test_resolve_dash_manifest_from_policy_with_dash_substitution() {
+ let policy_json =
+ r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_dash/*"}]}"#;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
+ let cf_b64 = b64.replace('+', "-");
+ let cookie = format!("CloudFront-Policy={cf_b64};CloudFront-Signature=abc;");
+ let resolved = resolve_dash_manifest_from_policy(&cookie);
+ assert_eq!(
+ resolved.as_deref(),
+ Some("https://sacdn.hakunaymatata.com/dash/test_dash/index.mpd")
+ );
+ }
+
+ #[test]
+ fn test_resolve_dash_manifest_from_policy_with_underscore_substitution() {
+ let policy_json = r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_underscore/*"}]}"#;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
+ let cf_b64 = b64.replace('=', "_");
+ let cookie = format!("CloudFront-Policy={cf_b64};CloudFront-Signature=abc;");
+ let resolved = resolve_dash_manifest_from_policy(&cookie);
+ assert_eq!(
+ resolved.as_deref(),
+ Some("https://sacdn.hakunaymatata.com/dash/test_underscore/index.mpd")
+ );
+ }
+
+ #[test]
+ fn test_resolve_dash_manifest_from_policy_with_tilde_substitution() {
+ let policy_json =
+ r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_tilde/*"}]}"#;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
+ let cf_b64 = b64.replace('/', "~");
+ let cookie = format!("CloudFront-Policy={cf_b64};CloudFront-Signature=abc;");
+ let resolved = resolve_dash_manifest_from_policy(&cookie);
+ assert_eq!(
+ resolved.as_deref(),
+ Some("https://sacdn.hakunaymatata.com/dash/test_tilde/index.mpd")
+ );
+ }
+
+ #[test]
+ fn test_resolve_dash_manifest_from_policy_restores_missing_padding() {
+ let policy_json =
+ r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_pad/*"}]}"#;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
+ let unpadded = b64.trim_end_matches('=');
+ let cookie = format!("CloudFront-Policy={unpadded};CloudFront-Signature=abc;");
+ let resolved = resolve_dash_manifest_from_policy(&cookie);
+ assert_eq!(
+ resolved.as_deref(),
+ Some("https://sacdn.hakunaymatata.com/dash/test_pad/index.mpd")
+ );
+ }
+
+ #[test]
+ fn test_resolve_dash_manifest_from_malformed_policy() {
+ assert_eq!(
+ resolve_dash_manifest_from_policy("CloudFront-Policy=invalid!!not_b64"),
+ None
+ );
+ assert_eq!(
+ resolve_dash_manifest_from_policy("CloudFront-Policy=e30="),
+ None
+ );
+ assert_eq!(
+ resolve_dash_manifest_from_policy("SomeOtherCookie=123"),
+ None
+ );
+ }
+
+ #[test]
+ fn test_resolve_dash_manifest_resource_conversion() {
+ let policy_json =
+ r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/example/*"}]}"#;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
+ let cookie = format!("CloudFront-Policy={b64};");
+ let resolved = resolve_dash_manifest_from_policy(&cookie);
+ assert_eq!(
+ resolved.as_deref(),
+ Some("https://sacdn.hakunaymatata.com/dash/example/index.mpd")
+ );
+ }
+
+ #[test]
+ fn test_notice_fallback_rejected_when_signed_policy_missing() {
+ let payload = json!({
+ "code": 0,
+ "data": {
+ "title": "Deprecation Notice Title",
+ "streams": [
+ {
+ "id": "1",
+ "format": "MP4",
+ "codecName": "h264",
+ "resolutions": "480",
+ "url": "https://macdn.aoneroom.com/other/2026/09/01/9a0461bc39da389663bf3dbb17091d3f.mp4",
+ "signCookie": ""
+ }
+ ]
+ }
+ });
+
+ let releases = moviebox_play_info_json_to_releases(&payload, 0, 0, "TestAgent/1.0");
+ assert!(
+ releases.is_empty(),
+ "Deprecation notice MP4 must be rejected"
+ );
+ }
+
+ #[test]
+ fn test_legitimate_direct_stream_url_fallback_preserved() {
+ let payload = json!({
+ "code": 0,
+ "data": {
+ "title": "Legitimate Movie",
+ "streams": [
+ {
+ "id": "1",
+ "format": "MP4",
+ "codecName": "h264",
+ "resolutions": "1080",
+ "url": "https://cdn.example.com/legitimate_movie.mp4",
+ "signCookie": ""
+ }
+ ]
+ }
+ });
+
+ let releases = moviebox_play_info_json_to_releases(&payload, 0, 0, "TestAgent/1.0");
+ assert_eq!(releases.len(), 1);
+ assert_eq!(
+ releases[0].direct_url(),
+ Some("https://cdn.example.com/legitimate_movie.mp4")
+ );
+ }
}
diff --git a/src/providers/moviebox/title.rs b/src/providers/moviebox/title.rs
index 90c51d4..b829ee2 100644
--- a/src/providers/moviebox/title.rs
+++ b/src/providers/moviebox/title.rs
@@ -87,6 +87,22 @@ pub fn clean_moviebox_title(raw_title: &str) -> String {
title = title[..s_idx].trim();
}
+ for sep in ['_', ' ', '.', '-'] {
+ if let Some(pos) = title.rfind(sep) {
+ let suffix = &title[pos + 1..];
+ let is_res = (suffix.ends_with('p') || suffix.ends_with('P'))
+ && suffix.len() > 1
+ && suffix[..suffix.len() - 1]
+ .chars()
+ .all(|c| c.is_ascii_digit())
+ && suffix[..suffix.len() - 1]
+ .parse::<u32>()
+ .is_ok_and(|r| (144..=8640).contains(&r));
+ if is_res {
+ title = title[..pos].trim();
+ }
+ }
+ }
let cleaned = title
.trim_end_matches(['-', ':', '_', '.', ' '])
.trim()
@@ -186,8 +202,12 @@ mod tests {
assert_eq!(clean_moviebox_title("Movie - Hindi Dub"), "Movie");
assert_eq!(clean_moviebox_title("Breaking Bad S01"), "Breaking Bad");
assert_eq!(clean_moviebox_title("Dark Season 2"), "Dark");
+ assert_eq!(
+ clean_moviebox_title("Ek Deewane Ki Deewaniyat_360P"),
+ "Ek Deewane Ki Deewaniyat"
+ );
+ assert_eq!(clean_moviebox_title("Interstellar_1080P"), "Interstellar");
}
-
#[test]
fn test_clean_moviebox_title_empty_and_whitespace() {
assert_eq!(clean_moviebox_title(""), "");
diff --git a/src/service.rs b/src/service.rs
index 19c3a2c..5d4861b 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -269,19 +269,18 @@ impl MovieBoxService {
}
pub async fn decode_poster(bytes: Vec<u8>) -> Option<Arc<image::DynamicImage>> {
- tokio::task::spawn_blocking(move || image::load_from_memory(&bytes))
- .await
- .ok()?
- .ok()
- .map(Arc::new)
-}
-
-pub fn downscale_for_cache(img: &Arc<image::DynamicImage>) -> Arc<image::DynamicImage> {
- const MAX_DIM: u32 = 512;
- if img.width().max(img.height()) <= MAX_DIM {
- return Arc::clone(img);
- }
- Arc::new(img.resize(MAX_DIM, MAX_DIM, image::imageops::FilterType::Triangle))
+ tokio::task::spawn_blocking(move || {
+ let img = image::load_from_memory(&bytes).ok()?;
+ const MAX_DIM: u32 = 512;
+ let downscaled = if img.width().max(img.height()) <= MAX_DIM {
+ img
+ } else {
+ img.resize(MAX_DIM, MAX_DIM, image::imageops::FilterType::Triangle)
+ };
+ Some(Arc::new(downscaled))
+ })
+ .await
+ .ok()?
}
pub fn metric_value(item: &serde_json::Value, keys: &[&str]) -> Option<f64> {
@@ -389,3 +388,22 @@ pub fn resolve_download_dir(custom_dir: Option<&Path>) -> PathBuf {
ensure_moviebox_subdir(&base_dir)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn test_decode_poster_caps_dimensions() {
+ let mut buffer = std::io::Cursor::new(Vec::new());
+ let img = image::DynamicImage::new_rgb8(800, 600);
+ img.write_to(&mut buffer, image::ImageFormat::Png).unwrap();
+ let bytes = buffer.into_inner();
+
+ let decoded = decode_poster(bytes).await.unwrap();
+ assert!(decoded.width() <= 512);
+ assert!(decoded.height() <= 512);
+ assert_eq!(decoded.width(), 512);
+ assert_eq!(decoded.height(), 384);
+ }
+}
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 0bc84de..e85e34b 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -489,6 +489,7 @@ impl App {
self.state.input_mode = InputMode::Normal;
if !query.starts_with('/') {
self.state.is_loading = true;
+ self.state.has_search_settled = false;
self.state.search_error = None;
}
self.state.search_suggestions.clear();
@@ -889,6 +890,8 @@ impl App {
if self.state.search_results.is_empty()
&& !self.state.search_query.trim().is_empty()
{
+ self.state.is_loading = true;
+ self.state.has_search_settled = false;
self.action_sender
.send(Action::Search {
query: self.state.search_query.trim().to_string(),
@@ -1026,7 +1029,7 @@ impl App {
}
}
}
- KeyCode::Char('q') => {
+ KeyCode::Char('q') | KeyCode::Char('Q') => {
self.action_sender.send(Action::Quit).ok();
}
KeyCode::Char('d') | KeyCode::Char('D') => {
@@ -1298,4 +1301,34 @@ mod tests {
assert!(app.state.search_results.is_empty());
assert_eq!(app.state.search_list_state.selected(), None);
}
+
+ #[tokio::test]
+ async fn test_browse_esc_returns_to_homepage() {
+ let mut app = App::new();
+ app.state.active_screen = crate::tui::state::Screen::Home;
+ app.state.input_mode = InputMode::Normal;
+ app.state.active_browse_preset = Some(crate::models::BrowsePreset::Trending);
+ app.state.search_results = vec![crate::models::SearchResult {
+ id: "1".to_string(),
+ title: "Awarapan 2".to_string(),
+ stype: 1,
+ release_year: "2026".to_string(),
+ provider: crate::models::ProviderKind::MovieBox,
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ }];
+ app.state.search_list_state.select(Some(0));
+
+ app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
+ .await;
+ while let Ok(action) = app.action_receiver.try_recv() {
+ app.handle_action(action).await;
+ }
+
+ assert!(app.state.active_browse_preset.is_none());
+ assert!(app.state.search_results.is_empty());
+ assert_eq!(app.state.search_list_state.selected(), None);
+ assert_eq!(app.state.input_mode, InputMode::Normal);
+ }
}
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 887038c..2bbcee1 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -676,7 +676,41 @@ impl App {
}
let results_y = 2;
- if row >= results_y && row < area.height.saturating_sub(1) {
+ if row >= results_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),
+ },
+ next_label,
+ ctrl_p,
+ self.state.is_tv_mode,
+ self.state.is_addon_mode,
+ );
+ let pos = ratatui::layout::Position::new(col, row);
+ if btn1.contains(pos) {
+ if self.state.is_tv_mode {
+ self.action_sender.send(Action::TvReloadPlaylists).ok();
+ } else if self.state.is_addon_mode {
+ self.action_sender.send(Action::ShowAddonManager).ok();
+ } else {
+ self.cycle_provider();
+ }
+ return None;
+ }
+ if btn2.contains(pos) {
+ self.state.clear_search_state();
+ self.state.input_mode = InputMode::Normal;
+ self.state.set_status_default("");
+ return None;
+ }
+ return None;
+ }
let metrics = self
.state
.result_metrics(area.height.saturating_sub(results_y + 1), area.width);
@@ -941,18 +975,24 @@ impl App {
let streams_count = self.state.selected_resources.len();
if streams_count > 0 {
- let list_start_y = streams_area.y.saturating_add(2);
+ let list_start_y = if streams_area.height >= 4 {
+ streams_area.y.saturating_add(2)
+ } else {
+ streams_area.y.saturating_add(1)
+ };
let list_end_y = streams_area.bottom().saturating_sub(1);
if row >= list_start_y && row < list_end_y {
- let clicked_stream_row = (row - list_start_y)
- .saturating_add(self.state.resource_list_state.offset() as u16);
- let target_idx =
- (clicked_stream_row as usize).min(streams_count.saturating_sub(1));
-
- let prev_selected = self.state.resource_list_state.selected();
- self.state.resource_list_state.select(Some(target_idx));
-
- if prev_selected == Some(target_idx) {
+ let relative_row = (row - list_start_y) as usize;
+ let clicked_stream_idx = self
+ .state
+ .resource_list_state
+ .offset()
+ .saturating_add(relative_row);
+
+ if clicked_stream_idx < streams_count {
+ self.state
+ .resource_list_state
+ .select(Some(clicked_stream_idx));
if self.state.is_playing {
self.state.notify(
NotificationKind::Warning,
@@ -1123,3 +1163,140 @@ fn click_in_picker(
Some(None)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::models::{
+ AudioTrackOption, MediaDetails, MediaType, ProviderKind, ProviderMediaId, Release,
+ };
+ use crate::tui::action::Action;
+ use crate::tui::state::DetailsPane;
+ use ratatui::layout::Rect;
+
+ #[test]
+ fn test_details_streams_panel_click_empty_space_does_not_open_stream() {
+ let mut app = App::new();
+ app.state.active_screen = crate::tui::state::Screen::Details;
+ app.state.details_pane = DetailsPane::Languages;
+ app.state.selected_details = Some(MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "test_movie".to_string(),
+ },
+ title: "Test Movie".to_string(),
+ media_type: MediaType::Movie,
+ year: Some("2025".to_string()),
+ description: Some("Short description".to_string()),
+ tagline: None,
+ imdb_rating: Some("4.6".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: Some("https://example.com/poster.jpg".to_string()),
+ duration: Some("2h".to_string()),
+ genres: vec![],
+ seasons: vec![],
+ dubs: vec![
+ AudioTrackOption {
+ subject_id: "1".to_string(),
+ language: "Original".to_string(),
+ label: "Original".to_string(),
+ },
+ AudioTrackOption {
+ subject_id: "2".to_string(),
+ language: "Hindi".to_string(),
+ label: "Hindi".to_string(),
+ },
+ ],
+ });
+ app.state.selected_resources = vec![Release {
+ provider: ProviderKind::MovieBox,
+ filename: "Movie.1080p.mkv".to_string(),
+ quality: Some("1080p".to_string()),
+ codec: Some("HEVC".to_string()),
+ language: None,
+ size_bytes: Some(1024 * 1024 * 1024),
+ season: None,
+ episode: None,
+ mirrors: vec![],
+ }];
+ app.state.resource_list_state.select(Some(0));
+
+ let area = Rect::new(0, 0, 120, 30);
+ let layout = crate::tui::screens::details::details_screen_layout(
+ area,
+ app.state.selected_details.as_ref(),
+ );
+ let bottom_area = layout.bottom_area;
+ let lower_chunks =
+ Layout::vertical([Constraint::Length(4), Constraint::Min(3)]).split(bottom_area);
+ let streams_area = lower_chunks[1];
+
+ let empty_space_row = streams_area.bottom().saturating_sub(3);
+ let action = app.handle_details_mouse(streams_area.x + 10, empty_space_row, area);
+ assert!(action.is_none());
+ assert_eq!(app.state.details_pane, DetailsPane::Streams);
+ assert_eq!(app.state.resource_list_state.selected(), Some(0));
+
+ let mut received_play = false;
+ while let Ok(act) = app.action_receiver.try_recv() {
+ if matches!(act, Action::PlayStream) {
+ received_play = true;
+ }
+ }
+ assert!(!received_play);
+
+ let stream_item_row = if streams_area.height >= 4 {
+ streams_area.y + 2
+ } else {
+ streams_area.y + 1
+ };
+ let action_stream = app.handle_details_mouse(streams_area.x + 10, stream_item_row, area);
+ assert!(action_stream.is_none());
+ assert_eq!(app.state.details_pane, DetailsPane::Streams);
+
+ let mut stream_played = false;
+ while let Ok(act) = app.action_receiver.try_recv() {
+ if matches!(act, Action::PlayStream) {
+ stream_played = true;
+ }
+ }
+ assert!(stream_played);
+ }
+
+ #[tokio::test]
+ async fn test_home_no_results_mouse_click_actions() {
+ let mut app = App::new();
+ app.state.active_screen = crate::tui::state::Screen::Home;
+ app.state.input_mode = crate::tui::state::InputMode::Normal;
+ app.state.active_provider = ProviderKind::FourKHdHub;
+ app.state.search_query.set_content("deewaniyat");
+ app.state.search_results = vec![];
+
+ let area = Rect::new(0, 0, 100, 30);
+ let results_y = 2;
+ 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),
+ },
+ next_label,
+ ctrl_p,
+ app.state.is_tv_mode,
+ app.state.is_addon_mode,
+ );
+
+ app.handle_home_mouse(btn2.x + 1, btn2.y, area);
+ assert!(app.state.search_query.is_empty());
+
+ app.state.search_query.set_content("deewaniyat");
+ app.handle_home_mouse(btn1.x + 1, btn1.y, area);
+ assert_ne!(app.state.active_provider, ProviderKind::FourKHdHub);
+ }
+}
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index c9b80d3..9112b92 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -24,9 +24,14 @@ impl App {
if self.state.is_tv_mode {
return;
}
- if provider == self.state.active_provider {
- return;
- }
+ let previous_query = if !self.state.search_query.trim().is_empty() {
+ Some(self.state.search_query.trim().to_string())
+ } else {
+ self.state
+ .selected_details
+ .as_ref()
+ .map(|details| details.title.trim().to_string())
+ };
self.prepare_image_soft_refresh();
self.reset_mode_state();
self.state.active_provider = provider;
@@ -36,6 +41,8 @@ impl App {
self.state.selected_episode = 1;
self.state.language_chosen = false;
self.state.stream_pool.clear();
+ self.state.has_streams_settled = false;
+ self.state.has_search_settled = false;
self.state
.cancel_download
.store(true, std::sync::atomic::Ordering::SeqCst);
@@ -64,9 +71,10 @@ impl App {
let _ = client.init().await;
});
}
- let trimmed = self.state.search_query.trim();
- if !trimmed.is_empty() && !trimmed.starts_with('/') {
- let query = trimmed.to_string();
+ if let Some(query) = previous_query.filter(|q| !q.is_empty() && !q.starts_with('/')) {
+ self.state.search_query.set_content(&query);
+ self.state.is_loading = true;
+ self.state.has_search_settled = false;
let context = self.prepare_search_request(&query);
self.run_search_request(query, false, context);
}
@@ -276,6 +284,7 @@ impl App {
self.state.selected_episode = ep;
self.state.resource_list_state.select(None);
self.state.stream_error = None;
+ self.state.has_streams_settled = false;
self.state.active_resource_request = self.state.active_resource_request.wrapping_add(1);
let memory_cached = self
@@ -362,6 +371,7 @@ impl App {
self.state.subtitle_popup = false;
self.state.is_download_subtitle_popup = false;
self.state.pending_play_link = None;
+ self.state.pending_playback_source = None;
self.state.pending_open_with = false;
self.state.subtitle_list.clear();
self.state.subtitle_list_state.select(None);
@@ -383,6 +393,17 @@ impl App {
}
match self.state.active_screen {
Screen::Home => {
+ if self.state.active_browse_preset.is_some()
+ || self.state.active_addon_catalog.is_some()
+ || self.state.is_homepage_mode
+ {
+ self.state.active_browse_preset = None;
+ self.state.active_addon_catalog = None;
+ self.state.is_homepage_mode = false;
+ self.state.clear_search_state();
+ self.state.set_status_default("");
+ return None;
+ }
if !self.state.search_results.is_empty() {
self.state.input_mode = InputMode::Editing;
self.state.favorites_focus = false;
@@ -440,6 +461,10 @@ impl App {
self.state.resource_list_state.select(None);
self.state.language_chosen = true;
self.state.language_list_state.select(Some(idx));
+ self.state.is_loading = true;
+ self.state.is_fetching_streams = true;
+ self.state.has_streams_settled = false;
+ self.state.stream_error = None;
if self.state.active_subject_id.as_deref() == Some(&next_id) {
if !self.state.stream_pool.contains_key(&next_id) {
self.state.set_status_default("Loading streams...");
@@ -720,8 +745,25 @@ impl App {
if self.state.subtitle_popup {
self.state.subtitle_popup = false;
let idx = self.state.subtitle_list_state.selected().unwrap_or(0);
- let sub_url = self.state.subtitle_list.get(idx).map(|(_, u)| u.clone());
- if let Some(link) = self.state.pending_play_link.take() {
+ let sub_url = self
+ .state
+ .subtitle_list
+ .get(idx)
+ .map(|(_, u)| u.clone())
+ .filter(|s| !s.is_empty());
+ if let Some(mut source) = self.state.pending_playback_source.take() {
+ source.subtitle = sub_url;
+ let default_player = self.preferred_playback_player(&source);
+ if let Some(player) = default_player {
+ self.action_sender
+ .send(Action::LaunchPlayback(player, source))
+ .ok();
+ } else {
+ self.action_sender
+ .send(Action::ShowPlaybackPicker(source))
+ .ok();
+ }
+ } else if let Some(link) = self.state.pending_play_link.take() {
self.action_sender
.send(Action::LaunchMpv(link, sub_url))
.ok();
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index bf5c8ec..6d9bedb 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -4,7 +4,7 @@ use crate::tui::text::parse_duration_seconds;
use crate::tui::{action::Action, overlay::NotificationKind, state::Screen};
impl App {
- fn preferred_playback_player(
+ pub(super) fn preferred_playback_player(
&self,
source: &crate::providers::models::PlaybackSource,
) -> Option<crate::tui::state::PlayerKind> {
@@ -417,8 +417,25 @@ impl App {
return None;
}
if self.state.active_screen == Screen::Details
- && let Some(link) = self.get_selected_link()
+ && let Some(release) = self.get_selected_release()
{
+ let Some(first_mirror) = release.mirrors.first().cloned() else {
+ self.state.is_resolving_playback = false;
+ self.state.notify(
+ NotificationKind::Error,
+ "Playback unavailable",
+ "No playable mirrors were found for this release.",
+ );
+ return None;
+ };
+ let direct_source = crate::providers::models::PlaybackSource {
+ provider: release.provider,
+ url: first_mirror.resolver_url.clone(),
+ headers: first_mirror.headers.clone(),
+ subtitle: None,
+ source_label: first_mirror.label.clone(),
+ };
+ let default_player = self.preferred_playback_player(&direct_source);
let subject_id = self
.state
.selected_details
@@ -433,9 +450,10 @@ impl App {
"Preparing playback",
"Fetching subtitles.",
);
+ self.state.pending_playback_source = Some(direct_source.clone());
let service = self.service.clone();
let sender = self.action_sender.clone();
- let link_clone = link.clone();
+ let source_clone = direct_source.clone();
tokio::spawn(async move {
let cached = tokio::task::spawn_blocking({
let subject_id = subject_id.clone();
@@ -447,7 +465,7 @@ impl App {
.flatten();
if let Some(res) = cached {
sender
- .send(Action::ShowSubtitlePopup(link_clone.clone(), res))
+ .send(Action::ShowSubtitlePopup(source_clone.url.clone(), res))
.ok();
return;
}
@@ -468,15 +486,31 @@ impl App {
&res_for_cache,
);
});
- sender.send(Action::ShowSubtitlePopup(link_clone, res)).ok();
+ sender
+ .send(Action::ShowSubtitlePopup(source_clone.url, res))
+ .ok();
}
_ => {
- sender.send(Action::LaunchMpv(link_clone, None)).ok();
+ if let Some(player) = default_player {
+ sender
+ .send(Action::LaunchPlayback(player, source_clone))
+ .ok();
+ } else {
+ sender.send(Action::ShowPlaybackPicker(source_clone)).ok();
+ }
}
}
});
} else {
- self.action_sender.send(Action::LaunchMpv(link, None)).ok();
+ if let Some(player) = default_player {
+ self.action_sender
+ .send(Action::LaunchPlayback(player, direct_source))
+ .ok();
+ } else {
+ self.action_sender
+ .send(Action::ShowPlaybackPicker(direct_source))
+ .ok();
+ }
}
} else {
self.state.is_resolving_playback = false;
@@ -496,7 +530,20 @@ impl App {
self.state.subtitle_list_state.select(Some(0));
self.state.pending_play_link = Some(link);
} else {
- self.action_sender.send(Action::LaunchMpv(link, None)).ok();
+ if let Some(source) = self.state.pending_playback_source.take() {
+ let default_player = self.preferred_playback_player(&source);
+ if let Some(player) = default_player {
+ self.action_sender
+ .send(Action::LaunchPlayback(player, source))
+ .ok();
+ } else {
+ self.action_sender
+ .send(Action::ShowPlaybackPicker(source))
+ .ok();
+ }
+ } else {
+ self.action_sender.send(Action::LaunchMpv(link, None)).ok();
+ }
}
}
Action::ShowDownloadSubtitlePopup(subtitles) => {
@@ -598,11 +645,16 @@ impl App {
self.state.is_resolving_playback = false;
self.state.player_picker_popup = false;
self.state.last_playback_launch = std::time::Instant::now();
- let headers = vec![(
- "User-Agent".to_string(),
- self.service.client.user_agent().to_string(),
- )];
- self.launch_player(kind, link, sub, headers);
+ if let Some(mut source) = self.state.pending_playback_source.take() {
+ source.subtitle = sub;
+ self.launch_player(kind, source.url, source.subtitle, source.headers);
+ } else {
+ let headers = vec![(
+ "User-Agent".to_string(),
+ self.service.client.user_agent().to_string(),
+ )];
+ self.launch_player(kind, link, sub, headers);
+ }
}
Action::LaunchPlayback(kind, source) => {
self.state.is_resolving_playback = false;
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 5e956a5..7d7f48e 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -115,6 +115,8 @@ impl App {
self.state.suggest_index = None;
self.state.search_suggestions.clear();
self.state.input_mode = InputMode::Normal;
+ self.state.is_loading = true;
+ self.state.has_search_settled = false;
self.action_sender
.send(Action::Search {
query,
@@ -233,6 +235,8 @@ impl App {
self.state.active_addon_catalog = None;
self.state.browse_list_state.select(None);
self.state.search_query.clear();
+ self.state.is_loading = true;
+ self.state.has_search_settled = false;
self.action_sender
.send(Action::FetchHomepage {
tab_id: "2".to_string(),
@@ -296,6 +300,7 @@ impl App {
self.state.current_page = page;
self.state.search_error = None;
self.state.is_loading = false;
+ self.state.has_search_settled = true;
if page <= 1 {
self.state.search_results.clear();
}
@@ -464,6 +469,7 @@ impl App {
context.provider.cache_key()
);
self.state.is_loading = false;
+ self.state.has_search_settled = true;
if page <= 1 {
self.state.search_results.clear();
self.state.search_list_state.select(None);
@@ -494,6 +500,7 @@ impl App {
return None;
}
self.state.is_loading = false;
+ self.state.has_search_settled = true;
if page == 1 {
self.state.search_results.clear();
self.state.search_error = None;
@@ -563,6 +570,7 @@ impl App {
}
log::error!("discover failed: {err}");
self.state.is_loading = false;
+ self.state.has_search_settled = true;
self.state.search_error = Some(format!("Discover failed: {err}"));
self.state.search_results.clear();
self.state.search_list_state.select(None);
@@ -830,11 +838,10 @@ impl App {
Action::SearchPosterLoaded(id, img_opt) => {
self.state.in_flight_posters.remove(&id);
if let Some(img) = img_opt {
- let cached = crate::service::downscale_for_cache(&img);
self.state
.image_cache
- .put(id.clone(), std::sync::Arc::clone(&cached));
- self.state.search_posters.put(id, cached);
+ .put(id.clone(), std::sync::Arc::clone(&img));
+ self.state.search_posters.put(id, img);
} else {
self.state.failed_posters.put(id, std::time::Instant::now());
}
@@ -1152,6 +1159,10 @@ impl App {
}
Action::InitStreamPool(subject_id) => {
+ self.state.is_loading = true;
+ self.state.is_fetching_streams = true;
+ self.state.has_streams_settled = false;
+ self.state.stream_error = None;
if self.provider_for_subject(&subject_id) != ProviderKind::MovieBox {
self.state
.stream_pool
@@ -1243,6 +1254,7 @@ impl App {
let request_id = self.state.active_resource_request;
self.state.is_loading = true;
self.state.is_fetching_streams = true;
+ self.state.has_streams_settled = false;
self.state.selected_resources.clear();
self.state.stream_error = None;
@@ -1780,6 +1792,7 @@ impl App {
self.state.selected_resources = filtered;
self.state.is_loading = false;
self.state.is_fetching_streams = false;
+ self.state.has_streams_settled = true;
self.state.stream_error = None;
self.state
.resource_list_state
@@ -1851,6 +1864,7 @@ impl App {
self.state.auto_play_on_ready = false;
self.state.is_loading = false;
self.state.is_fetching_streams = false;
+ self.state.has_streams_settled = true;
self.state.selected_resources.clear();
self.state.resource_list_state.select(None);
self.state.stream_error = Some(err.clone());
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index 01c7b20..d72e493 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -475,6 +475,7 @@ impl App {
self.state.selected_details = None;
self.state.selected_resources.clear();
self.state.is_loading = true;
+ self.state.has_search_settled = false;
self.state.search_error = None;
self.state.search_list_state.select(Some(0));
self.state.search_suggestions.clear();
@@ -504,6 +505,7 @@ impl App {
self.state.selected_details = None;
self.state.selected_resources.clear();
self.state.is_loading = true;
+ self.state.has_search_settled = false;
self.state.search_error = None;
self.state.search_list_state.select(Some(0));
self.state.search_suggestions.clear();
@@ -592,6 +594,7 @@ impl App {
self.state.current_page = page;
self.state.active_screen = Screen::Home;
self.state.is_loading = true;
+ self.state.has_search_settled = false;
self.state.search_error = None;
if page == 1 {
self.state.active_preview_request = self.state.active_preview_request.wrapping_add(1);
@@ -877,8 +880,8 @@ impl App {
let visible = self.state.effective_visible_items().max(6);
let base_start = offset.min(selected);
- let start = base_start.saturating_sub(6);
- let end = (offset + visible + 14).min(total);
+ let start = base_start.saturating_sub(2);
+ let end = (offset + visible + 4).min(total);
if start < end {
let slice: Vec<(String, Option<String>, ProviderKind)> = self.state.search_results
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index 9abfd3b..0011059 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -1,4 +1,4 @@
-use crate::models::{MediaDetails, ProviderKind};
+use crate::models::MediaDetails;
pub(crate) use crate::tui::widgets::{extract_media_tags, resolution_badge_spans};
use crate::tui::{state::AppState, theme::Theme};
use ratatui::{
@@ -32,8 +32,8 @@ impl DetailsLayoutTier {
pub(crate) fn header_height(self, area: Rect, details: Option<&MediaDetails>) -> u16 {
let (minimum, maximum, synopsis_limit, reserved_width) = match self {
- Self::Wide => (5, 11, 4, 30),
- Self::Medium => (5, 10, 3, 24),
+ Self::Wide => (5, 11, 4, 18),
+ Self::Medium => (5, 10, 3, 16),
Self::Narrow => (4, 9, 3, 4),
Self::Tiny => (4, 7, 2, 4),
};
@@ -49,28 +49,25 @@ impl DetailsLayoutTier {
return minimum.min(maximum);
};
let synopsis = details.description.as_deref().unwrap_or_default();
- let show_poster = area.width >= 75 && details.poster_url.is_some();
+ let show_poster = !matches!(self, Self::Tiny | Self::Narrow)
+ && area.width >= 75
+ && details.poster_url.is_some();
let text_width = area
.width
.saturating_sub(if show_poster { reserved_width } else { 4 })
.max(20) as usize;
let title = &details.title;
- let title_rows = (crate::tui::text::width(title) + 14)
+ let title_rows = crate::tui::text::width(title)
.div_ceil(text_width)
.clamp(1, 2);
- let has_tagline = details
- .tagline
- .as_ref()
- .is_some_and(|t| !t.trim().is_empty());
let has_cast = details.stars.as_ref().is_some_and(|s| !s.trim().is_empty());
- let has_prints = details
- .prints
+ let has_director = details
+ .director
.as_ref()
- .is_some_and(|p| !p.trim().is_empty());
- let meta_lines = title_rows
- + (if has_tagline { 1 } else { 0 })
- + (if has_cast { 1 } else { 0 })
- + (if has_prints { 1 } else { 0 });
+ .is_some_and(|d| !d.trim().is_empty());
+ let has_genres = !details.genres.is_empty();
+ let has_extra_meta = has_cast || has_director || has_genres;
+ let meta_lines = title_rows + 1 + 1 + (if has_extra_meta { 1 } else { 0 });
let synopsis_rows = if synopsis.trim().is_empty() {
0
} else {
@@ -79,9 +76,9 @@ impl DetailsLayoutTier {
.clamp(1, synopsis_limit)
};
let content_rows = if show_poster {
- (meta_lines + 1 + synopsis_rows).max(7)
+ (meta_lines + synopsis_rows).max(5)
} else {
- meta_lines + 1 + synopsis_rows
+ meta_lines + synopsis_rows
};
(content_rows as u16 + 2).clamp(minimum, maximum)
}
@@ -331,7 +328,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
"N/A".to_string()
};
let duration = details.duration.as_deref().unwrap_or("N/A");
- let country = "N/A";
let imdb_rating = details.imdb_rating.as_deref().unwrap_or("N/A");
let tagline = details.tagline.as_deref();
@@ -354,7 +350,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
frame.render_widget(details_block.clone(), header_area);
let show_poster = !matches!(tier, DetailsLayoutTier::Tiny | DetailsLayoutTier::Narrow)
- && inner_area.height >= 7
+ && inner_area.height >= 5
&& inner_area.width >= 75;
let poster_width = if show_poster {
let width_for_height = state
@@ -363,15 +359,15 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.zip(state.image_picker.as_ref())
.map(|(image, picker)| {
let font_size = picker.font_size();
- let font_w = font_size.width;
- let font_h = font_size.height;
+ let font_w = font_size.width.max(1);
+ let font_h = font_size.height.max(1);
let area_h_px = (inner_area.height as f32) * (font_h as f32);
- let aspect = image.width() as f32 / image.height() as f32;
+ let aspect = image.width() as f32 / (image.height() as f32).max(1.0);
let area_w_px = area_h_px * aspect;
- ((area_w_px / font_w as f32).ceil() as u16).max(1)
+ ((area_w_px / font_w as f32).round() as u16).max(1)
})
- .unwrap_or_else(|| (inner_area.height as f32 * 1.5).ceil() as u16);
- width_for_height.clamp(14, 28)
+ .unwrap_or_else(|| ((inner_area.height as f32 * (4.0 / 3.0)).round() as u16).max(6));
+ width_for_height.clamp(8, 22)
} else {
0
};
@@ -379,7 +375,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let meta_constraints = if show_poster {
vec![
Constraint::Length(poster_width),
- Constraint::Length(1),
+ Constraint::Length(2),
Constraint::Min(20),
]
} else {
@@ -432,7 +428,13 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.border_type(crate::tui::overlay::border_type(state.basic_terminal))
.border_style(theme.surface0);
let spinner = stream_loading_spinner(state.tick_count, state.basic_terminal);
- let placeholder_text = if state.basic_terminal {
+ let placeholder_text = if poster_area.height <= 5 {
+ if state.basic_terminal {
+ format!("[Poster]\n{spinner}")
+ } else {
+ format!("🖼️\n{spinner}")
+ }
+ } else if state.basic_terminal {
format!("\n\n [Poster]\n {spinner}")
} else {
format!("\n\n 🖼️\n {spinner}")
@@ -449,145 +451,197 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
inner_area
};
- let mut info_lines = vec![];
+ let text_width = meta_area.width as usize;
+ let total_height = meta_area.height as usize;
+
+ let mut rendered_lines: Vec<Line> = Vec::new();
+
+ let title_w = crate::tui::text::width(&title);
+ if title_w <= text_width {
+ rendered_lines.push(Line::from(vec![Span::styled(
+ title.clone(),
+ theme.title.add_modifier(Modifier::BOLD),
+ )]));
+ } else {
+ let wrapped_title = crate::tui::text::wrap_text(&title, text_width);
+ for line in wrapped_title.into_iter().take(2) {
+ rendered_lines.push(Line::from(vec![Span::styled(
+ line,
+ theme.title.add_modifier(Modifier::BOLD),
+ )]));
+ }
+ }
let bullet_sep = if state.basic_terminal { " - " } else { " · " };
- let mut header_spans = vec![
- Span::styled(title.clone(), theme.title.add_modifier(Modifier::BOLD)),
- Span::styled(bullet_sep, theme.overlay0),
+ let mut badge_spans = vec![
Span::styled(year, theme.subtext1),
Span::styled(bullet_sep, theme.overlay0),
Span::styled(type_str, theme.accent.add_modifier(Modifier::BOLD)),
];
if duration != "N/A" {
- header_spans.push(Span::styled(bullet_sep, theme.overlay0));
- header_spans.push(Span::styled(duration, theme.subtext1));
+ badge_spans.push(Span::styled(bullet_sep, theme.overlay0));
+ badge_spans.push(Span::styled(duration, theme.subtext1));
}
if imdb_rating != "N/A" {
- header_spans.push(Span::styled(bullet_sep, theme.overlay0));
+ badge_spans.push(Span::styled(bullet_sep, theme.overlay0));
if state.basic_terminal {
- header_spans.push(Span::styled("IMDb ", theme.rating));
+ badge_spans.push(Span::styled("IMDb ", theme.rating));
} else {
- header_spans.push(Span::styled("★ ", theme.rating));
+ badge_spans.push(Span::styled("★ ", theme.rating));
}
- header_spans.push(Span::styled(
+ badge_spans.push(Span::styled(
imdb_rating,
theme.rating.add_modifier(Modifier::BOLD),
));
}
- info_lines.push(Line::from(header_spans));
+ let audio_str = details
+ .audios
+ .as_deref()
+ .filter(|s| !s.trim().is_empty() && *s != "N/A")
+ .map(|s| s.to_string())
+ .or_else(|| {
+ if !details.dubs.is_empty() {
+ let mut unique_langs = Vec::new();
+ for dub in &details.dubs {
+ let lang = clean_language_name(&dub.language);
+ if !unique_langs.contains(&lang) {
+ unique_langs.push(lang);
+ }
+ }
+ if !unique_langs.is_empty() {
+ Some(unique_langs.join(", "))
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ });
- if let Some(t) = tagline {
- if !t.trim().is_empty() {
- info_lines.push(Line::from(vec![Span::styled(
- format!("\"{t}\""),
- theme.subtext1.add_modifier(Modifier::ITALIC),
- )]));
- }
+ if let Some(audios) = audio_str {
+ badge_spans.push(Span::styled(bullet_sep, theme.overlay1));
+ badge_spans.push(Span::styled(
+ "Audio: ",
+ theme.subtext1.add_modifier(Modifier::BOLD),
+ ));
+ badge_spans.push(Span::styled(audios, theme.accent));
}
- let mut meta_spans = Vec::new();
- let mut add_meta_item = |label: &'static str, value: &str, color: Color| {
- if value != "N/A" && !value.is_empty() {
- if !meta_spans.is_empty() {
- meta_spans.push(Span::styled(
- bullet_sep,
- theme.overlay0.add_modifier(Modifier::DIM),
- ));
- }
- meta_spans.push(Span::styled(
- format!("{label}: "),
- theme.overlay0.add_modifier(Modifier::BOLD),
- ));
- meta_spans.push(Span::styled(value.to_string(), Style::default().fg(color)));
- }
- };
+ let provider_name = details.id.provider.label();
+ if !provider_name.is_empty() {
+ badge_spans.push(Span::styled(bullet_sep, theme.overlay1));
+ badge_spans.push(Span::styled(provider_name.to_string(), theme.subtext1));
+ }
- add_meta_item(
- "Genre",
- &genres,
- theme_color(theme.subtext1, theme.text.fg.unwrap_or(Color::White)),
- );
- add_meta_item(
- "Director",
- details.director.as_deref().unwrap_or("N/A"),
- theme_color(theme.subtext1, theme.text.fg.unwrap_or(Color::White)),
- );
- add_meta_item(
- "Cast",
- details.stars.as_deref().unwrap_or("N/A"),
- theme_color(theme.subtext1, theme.text.fg.unwrap_or(Color::White)),
- );
- if !meta_spans.is_empty() {
- info_lines.push(Line::from(meta_spans));
+ rendered_lines.push(Line::from(badge_spans));
+
+ if let Some(t) = tagline.filter(|t| !t.trim().is_empty()) {
+ rendered_lines.push(Line::from(vec![Span::styled(
+ format!("\"{t}\""),
+ theme.subtext1.add_modifier(Modifier::ITALIC),
+ )]));
}
- let mut tech_spans = Vec::new();
- let mut add_tech_item = |label: &'static str, value: &str, color: Color| {
- if value != "N/A" && !value.is_empty() {
- if !tech_spans.is_empty() {
- tech_spans.push(Span::styled(
- bullet_sep,
- theme.overlay0.add_modifier(Modifier::DIM),
- ));
- }
- tech_spans.push(Span::styled(
- format!("{label}: "),
- theme.overlay0.add_modifier(Modifier::BOLD),
- ));
- tech_spans.push(Span::styled(value.to_string(), Style::default().fg(color)));
+ let mut extra_meta_spans = Vec::new();
+ if !details.genres.is_empty() {
+ extra_meta_spans.push(Span::styled(
+ "Genre: ",
+ theme.subtext1.add_modifier(Modifier::BOLD),
+ ));
+ extra_meta_spans.push(Span::styled(
+ genres.clone(),
+ theme_color(theme.subtext1, theme.text.fg.unwrap_or(Color::White)),
+ ));
+ }
+ if let Some(dir) = details
+ .director
+ .as_deref()
+ .filter(|d| !d.trim().is_empty() && *d != "N/A")
+ {
+ if !extra_meta_spans.is_empty() {
+ extra_meta_spans.push(Span::styled(bullet_sep, theme.overlay1));
}
- };
+ extra_meta_spans.push(Span::styled(
+ "Director: ",
+ theme.subtext1.add_modifier(Modifier::BOLD),
+ ));
+ extra_meta_spans.push(Span::styled(
+ dir.to_string(),
+ theme_color(theme.subtext1, theme.text.fg.unwrap_or(Color::White)),
+ ));
+ }
+ if let Some(cast) = details
+ .stars
+ .as_deref()
+ .filter(|s| !s.trim().is_empty() && *s != "N/A")
+ {
+ if !extra_meta_spans.is_empty() {
+ extra_meta_spans.push(Span::styled(bullet_sep, theme.overlay1));
+ }
+ extra_meta_spans.push(Span::styled(
+ "Cast: ",
+ theme.subtext1.add_modifier(Modifier::BOLD),
+ ));
+ extra_meta_spans.push(Span::styled(
+ cast.to_string(),
+ theme_color(theme.subtext1, theme.text.fg.unwrap_or(Color::White)),
+ ));
+ }
+ let has_extra_meta = !extra_meta_spans.is_empty();
- add_tech_item("Country", country, theme_color(theme.overlay1, Color::Gray));
- add_tech_item(
- "Prints",
- details.prints.as_deref().unwrap_or("N/A"),
- theme_color(theme.lavender, Color::Cyan),
- );
- add_tech_item(
- "Audio",
- details.audios.as_deref().unwrap_or("N/A"),
- theme_color(theme.accent, Color::Yellow),
- );
+ let reserved_bottom = if has_extra_meta { 1 } else { 0 };
+ let remaining_height = total_height.saturating_sub(rendered_lines.len() + reserved_bottom);
+ let (include_spacer, max_synopsis_lines) = if remaining_height >= 2 {
+ (true, remaining_height.saturating_sub(1))
+ } else {
+ (false, remaining_height)
+ };
- if !tech_spans.is_empty() {
- info_lines.push(Line::from(tech_spans));
+ if include_spacer {
+ rendered_lines.push(Line::from(""));
}
- let info_height = info_lines.len() as u16;
- let meta_chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([Constraint::Length(info_height), Constraint::Min(0)])
- .split(meta_area);
-
- let info_p = Paragraph::new(info_lines);
- frame.render_widget(info_p, meta_chunks[0]);
-
- let max_lines = meta_chunks[1].height as usize;
- let text_width = meta_chunks[1].width as usize;
- let mut wrapped = crate::tui::text::wrap_text(intro, text_width);
- if wrapped.len() > max_lines {
- wrapped.truncate(max_lines);
- if let Some(last) = wrapped.last_mut() {
- let last_w = crate::tui::text::width(last);
- if last_w + 3 <= text_width {
- last.push_str("...");
- } else {
- let truncated =
- crate::tui::text::truncate_width(last, text_width.saturating_sub(3));
- *last = format!("{}...", truncated);
+
+ if max_synopsis_lines > 0 {
+ let mut wrapped_synopsis = crate::tui::text::wrap_text(intro, text_width);
+ if wrapped_synopsis.len() > max_synopsis_lines {
+ wrapped_synopsis.truncate(max_synopsis_lines);
+ if let Some(last) = wrapped_synopsis.last_mut() {
+ let last_w = crate::tui::text::width(last);
+ if last_w + 3 <= text_width {
+ last.push_str("...");
+ } else {
+ let truncated =
+ crate::tui::text::truncate_width(last, text_width.saturating_sub(3));
+ *last = format!("{truncated}...");
+ }
}
}
+ for line in wrapped_synopsis {
+ rendered_lines.push(Line::from(vec![Span::styled(line, theme.subtext1)]));
+ }
}
- let syn_lines: Vec<Line> = wrapped
- .into_iter()
- .map(|line| Line::from(vec![Span::styled(line, theme.subtext1)]))
- .collect();
- let intro_p = Paragraph::new(syn_lines);
- frame.render_widget(intro_p, meta_chunks[1]);
+
+ if has_extra_meta {
+ rendered_lines.push(Line::from(extra_meta_spans));
+ }
+
+ let top_offset = total_height.saturating_sub(rendered_lines.len()) / 2;
+ let final_lines = if top_offset > 0 {
+ let mut padded = Vec::with_capacity(total_height);
+ for _ in 0..top_offset {
+ padded.push(Line::from(""));
+ }
+ padded.extend(rendered_lines);
+ padded
+ } else {
+ rendered_lines
+ };
+
+ 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();
@@ -889,12 +943,15 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
unfocused_border_style(theme)
};
+ let list = &state.selected_resources;
+ let visible_count = list.len();
+
let streams_title = if streams_count > 0 {
let selected = state
.resource_list_state
.selected()
.unwrap_or(0)
- .min(streams_count.saturating_sub(1));
+ .min(visible_count.saturating_sub(1));
let marker = if streams_focused {
focus_title_marker(state.basic_terminal)
} else {
@@ -902,12 +959,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
};
let avail = streams_area.width.saturating_sub(4) as usize;
let title_full = format!(
- " {marker}Streams ({streams_count}) · {}/{} ",
+ " {marker}Streams ({visible_count}) · {}/{} ",
selected + 1,
- streams_count
+ visible_count
);
if avail > 0 && crate::tui::text::width(&title_full) > avail {
- let title_medium = format!(" {marker}Streams ({streams_count}) ");
+ let title_medium = format!(" {marker}Streams ({visible_count}) ");
if crate::tui::text::width(&title_medium) <= avail {
title_medium
} else {
@@ -933,7 +990,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.border_style(streams_border)
.padding(ratatui::widgets::Padding::horizontal(1));
- let list = &state.selected_resources;
if !list.is_empty() {
let selected_idx = state.resource_list_state.selected();
@@ -941,9 +997,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.iter()
.enumerate()
.map(|(i, file)| {
- let resolution = file.resolution_u64() as i64;
+ let resolution = file.resolution_i64();
let codec = file.codec.as_deref().unwrap_or("None");
- let duration_str = "--:--".to_string();
let size_formatted = file
.size_bytes
@@ -969,10 +1024,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
metadata_style(theme)
};
- let is_fourk = file.provider == ProviderKind::FourKHdHub;
let release_title = crate::tui::text::clean_stream_text(&file.filename);
let upload_by = crate::tui::text::clean_stream_text(file.source_label());
- let source_count = file.mirrors.len() as u64;
let is_ultra_compact = streams_area.width < 58;
let is_compact = streams_area.width < 85;
let is_wide = streams_area.width >= 115;
@@ -1011,15 +1064,6 @@ 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 duration_col = if is_fourk && source_count > 0 {
- format!(
- "{source_count} mirr{}",
- if source_count == 1 { "or" } else { "ors" }
- )
- } else {
- duration_str
- };
-
if is_ultra_compact {
stream_spans.push(Span::styled(
crate::tui::text::truncate_width(&release_title, stream_width),
@@ -1041,10 +1085,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
format!("{:<20} ", crate::tui::text::truncate_width(&tags_col, 20)),
secondary_style,
));
- stream_spans.push(Span::styled(
- format!("{duration_col:>8} "),
- secondary_style,
- ));
stream_spans.push(Span::styled(
format!("{:<14} ", crate::tui::text::truncate_width(&upload_by, 14)),
secondary_style,
@@ -1060,11 +1100,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
tags_or_codec
};
stream_spans.push(Span::styled(
- format!("{:<12} ", crate::tui::text::truncate_width(&tags_col, 12)),
- secondary_style,
- ));
- stream_spans.push(Span::styled(
- format!("{duration_col:>8} "),
+ format!("{:<20} ", crate::tui::text::truncate_width(&tags_col, 20)),
secondary_style,
));
stream_spans.push(Span::styled(
@@ -1134,6 +1170,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let waiting_for_language = has_multiple_dubs && !state.language_chosen;
let has_error = state.stream_error.is_some();
+ let is_loading_streams = state.is_fetching_streams
+ || state.is_loading
+ || state.pending_episode_fetch.is_some()
+ || !state.has_streams_settled;
+
let msg = if waiting_for_language {
"Choose an audio track to load streams.".to_string()
} else if let Some(error) = &state.stream_error {
@@ -1144,24 +1185,31 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
} else {
format!("{error} — press r to retry or Ctrl+P to switch provider.")
}
- } else if state.is_fetching_streams || state.is_loading {
+ } else if is_loading_streams {
let spinner = stream_loading_spinner(state.tick_count, state.basic_terminal);
if state.basic_terminal {
format!("Loading streams {spinner}")
} else {
format!("{spinner} Loading streams...")
}
- } else {
+ } else if state.has_streams_settled && state.selected_resources.is_empty() {
format!(
"No stream sources found on {provider_label} — press Ctrl+P to try another provider, or r to retry."
)
+ } else {
+ let spinner = stream_loading_spinner(state.tick_count, state.basic_terminal);
+ if state.basic_terminal {
+ format!("Loading streams {spinner}")
+ } else {
+ format!("{spinner} Loading streams...")
+ }
};
let style = if has_error {
theme.error
} else if waiting_for_language {
theme.text_dim
- } else if state.is_fetching_streams || state.is_loading {
+ } else if is_loading_streams {
theme.lavender
} else {
theme.text_dim
@@ -1300,7 +1348,9 @@ pub(crate) fn episode_confirm_summary(state: &AppState) -> Vec<String> {
fn selected_stream_summary(state: &AppState) -> Option<String> {
let idx = state.resource_list_state.selected().unwrap_or(0);
let resource = state.selected_resources.get(idx)?;
- let resolution = if resource.resolution_u64() > 0 {
+ let resolution = if resource.is_multi_resolution() {
+ Some("Multi-Res".to_string())
+ } else if resource.resolution_u64() > 0 {
Some(format!("{}p", resource.resolution_u64()))
} else {
None
@@ -1577,7 +1627,7 @@ fn render_workflow(
}
fn stream_table_header_spans(width: u16, theme: &Theme) -> Vec<Span<'static>> {
- let header_style = theme.overlay0.add_modifier(Modifier::BOLD);
+ let header_style = theme.subtext1.add_modifier(Modifier::BOLD);
if width < 58 {
vec![Span::styled(" RES SIZE RELEASE", header_style)]
} else if width < 85 {
@@ -1587,12 +1637,12 @@ fn stream_table_header_spans(width: u16, theme: &Theme) -> Vec<Span<'static>> {
)]
} else if width < 115 {
vec![Span::styled(
- " RES SIZE MEDIA TAGS DURATION RELEASE",
+ " RES SIZE MEDIA TAGS RELEASE",
header_style,
)]
} else {
vec![Span::styled(
- " RES SIZE MEDIA TAGS DURATION UPLOADER RELEASE",
+ " RES SIZE MEDIA TAGS SOURCE RELEASE",
header_style,
)]
}
@@ -1666,10 +1716,22 @@ fn details_footer(
theme,
));
secondary.extend(footer_group("f", fav_label, false, theme));
+ secondary.extend(footer_group(
+ crate::tui::text::CTRL_P_STR,
+ "Provider",
+ false,
+ theme,
+ ));
secondary.extend(footer_group("Esc", "Back", false, theme));
} else if is_languages {
primary.extend(footer_group("Enter", "Select", true, theme));
primary.extend(footer_group("f", fav_label, false, theme));
+ secondary.extend(footer_group(
+ crate::tui::text::CTRL_P_STR,
+ "Provider",
+ false,
+ theme,
+ ));
secondary.extend(footer_group("Tab", "Streams", false, theme));
secondary.extend(footer_group("Esc", "Back", false, theme));
} else if is_seasons {
@@ -1685,6 +1747,12 @@ fn details_footer(
theme,
));
primary.extend(footer_group("f", fav_label, false, theme));
+ secondary.extend(footer_group(
+ crate::tui::text::CTRL_P_STR,
+ "Provider",
+ false,
+ theme,
+ ));
secondary.extend(footer_group("Tab", "Streams", false, theme));
secondary.extend(footer_group("Esc", "Back", false, theme));
} else if is_episodes {
@@ -1700,11 +1768,23 @@ fn details_footer(
theme,
));
primary.extend(footer_group("f", fav_label, false, theme));
+ secondary.extend(footer_group(
+ crate::tui::text::CTRL_P_STR,
+ "Provider",
+ false,
+ theme,
+ ));
secondary.extend(footer_group("Tab", "Streams", false, theme));
secondary.extend(footer_group("Esc", "Back", false, theme));
} else {
primary.extend(footer_group("Enter", "Select", true, theme));
primary.extend(footer_group("f", fav_label, false, theme));
+ secondary.extend(footer_group(
+ crate::tui::text::CTRL_P_STR,
+ "Provider",
+ false,
+ theme,
+ ));
secondary.extend(footer_group("Tab", "Streams", false, theme));
secondary.extend(footer_group("Esc", "Back", false, theme));
}
@@ -1770,8 +1850,13 @@ mod tests {
let spans_sd = resolution_badge_spans(480, &theme, false);
assert_eq!(spans_sd[0].content, " 480p ");
+ let spans_multi = resolution_badge_spans(-1, &theme, false);
+ assert_eq!(spans_multi[0].content, " Multi ");
+
let basic_4k = resolution_badge_spans(2160, &theme, true);
assert_eq!(basic_4k[0].content.trim(), "[4K]");
+ let basic_multi = resolution_badge_spans(-1, &theme, true);
+ assert_eq!(basic_multi[0].content.trim(), "[Multi]");
}
#[test]
@@ -1871,6 +1956,9 @@ mod tests {
assert!(content.contains("RES"));
assert!(content.contains("SIZE"));
assert!(content.contains("MEDIA TAGS"));
+ assert!(content.contains("SOURCE"));
+ assert!(!content.contains("DURATION"));
+ assert!(!content.contains("--:--"));
assert!(content.contains("1080p"));
assert!(content.contains("720p"));
assert!(content.contains("1.0GB"));
@@ -2325,4 +2413,188 @@ mod tests {
assert!(content.contains("Breaking Bad"));
assert!(content.contains("Portuguese (Brazil)"));
}
+ #[test]
+ fn test_details_header_compact_content_height() {
+ let details = MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "ek_deewane".to_string(),
+ },
+ title: "Ek Deewane Ki Deewaniyat".to_string(),
+ media_type: MediaType::Movie,
+ year: Some("2025".to_string()),
+ description: Some("When a powerful politician falls for a strong-willed superstar, their passionate romance quickly spirals into a dangerous game of obsession, pride, and heartbreak.".to_string()),
+ tagline: None,
+ imdb_rating: Some("4.6".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: Some("https://example.com/poster.jpg".to_string()),
+ duration: Some("2h 20m".to_string()),
+ genres: vec![],
+ seasons: vec![],
+ dubs: vec![
+ AudioTrackOption {
+ subject_id: "1".to_string(),
+ language: "Original Audio".to_string(),
+ label: "Original Audio".to_string(),
+ },
+ AudioTrackOption {
+ subject_id: "2".to_string(),
+ language: "Hindi dub".to_string(),
+ label: "Hindi dub".to_string(),
+ },
+ ],
+ };
+
+ let area = Rect::new(0, 0, 120, 30);
+ let tier = DetailsLayoutTier::for_area(area);
+ let height = tier.header_height(area, Some(&details));
+ assert_eq!(height, 7);
+ }
+
+ #[test]
+ fn test_details_audio_fallback_from_dubs() {
+ 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: "ek_deewane".to_string(),
+ },
+ title: "Ek Deewane Ki Deewaniyat".to_string(),
+ media_type: MediaType::Movie,
+ year: Some("2025".to_string()),
+ description: Some(
+ "When a powerful politician falls for a strong-willed superstar.".to_string(),
+ ),
+ tagline: None,
+ imdb_rating: Some("4.6".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: Some("https://example.com/poster.jpg".to_string()),
+ duration: Some("2h 20m".to_string()),
+ genres: vec![],
+ seasons: vec![],
+ dubs: vec![
+ AudioTrackOption {
+ subject_id: "1".to_string(),
+ language: "Original Audio".to_string(),
+ label: "Original Audio".to_string(),
+ },
+ AudioTrackOption {
+ subject_id: "2".to_string(),
+ language: "Hindi dub".to_string(),
+ label: "Hindi dub".to_string(),
+ },
+ ],
+ }),
+ ..Default::default()
+ };
+ let theme = Theme::mocha();
+
+ 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("Ek Deewane Ki Deewaniyat"));
+ assert!(content.contains("2025"));
+ assert!(content.contains("Movie"));
+ assert!(content.contains("Audio: Original, Hindi"));
+ assert!(content.contains("MovieBox"));
+ }
+
+ #[test]
+ fn test_details_no_flash_on_unsettled_streams() {
+ 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: "ek_deewane".to_string(),
+ },
+ title: "Ek Deewane Ki Deewaniyat".to_string(),
+ media_type: MediaType::Movie,
+ year: Some("2025".to_string()),
+ description: Some("Description".to_string()),
+ tagline: None,
+ imdb_rating: Some("4.6".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: Some("2h 20m".to_string()),
+ genres: vec![],
+ seasons: vec![],
+ dubs: vec![
+ AudioTrackOption {
+ subject_id: "1".to_string(),
+ language: "Original".to_string(),
+ label: "Original".to_string(),
+ },
+ AudioTrackOption {
+ subject_id: "2".to_string(),
+ language: "Hindi".to_string(),
+ label: "Hindi".to_string(),
+ },
+ ],
+ }),
+ language_chosen: true,
+ has_streams_settled: false,
+ is_fetching_streams: false,
+ is_loading: false,
+ selected_resources: vec![],
+ ..Default::default()
+ };
+ let theme = Theme::mocha();
+
+ terminal
+ .draw(|frame| {
+ draw(frame, frame.area(), &mut state, &theme);
+ })
+ .unwrap();
+
+ let content_unsettled = terminal
+ .backend()
+ .buffer()
+ .content()
+ .iter()
+ .map(|c| c.symbol())
+ .collect::<String>();
+
+ assert!(content_unsettled.contains("Loading streams"));
+ assert!(!content_unsettled.contains("No stream sources found"));
+
+ state.has_streams_settled = true;
+ terminal
+ .draw(|frame| {
+ draw(frame, frame.area(), &mut state, &theme);
+ })
+ .unwrap();
+
+ let content_settled = terminal
+ .backend()
+ .buffer()
+ .content()
+ .iter()
+ .map(|c| c.symbol())
+ .collect::<String>();
+
+ assert!(content_settled.contains("No stream sources found"));
+ }
}
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 670ab00..2986cc7 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -23,15 +23,21 @@ enum SearchViewState {
fn search_view_state(state: &AppState) -> SearchViewState {
if state.input_mode == InputMode::Editing {
SearchViewState::Editing
- } else if state.is_loading {
+ } else if state.is_loading
+ || (!state.has_search_settled
+ && (!state.search_query.trim().is_empty()
+ || state.active_browse_preset.is_some()
+ || state.active_addon_catalog.is_some()))
+ {
SearchViewState::Loading
} else if state.search_error.is_some() {
SearchViewState::Error
} else if !state.search_results.is_empty() {
SearchViewState::Results
- } else if !state.search_query.trim().is_empty()
- || state.active_browse_preset.is_some()
- || state.active_addon_catalog.is_some()
+ } else if state.has_search_settled
+ && (!state.search_query.trim().is_empty()
+ || state.active_browse_preset.is_some()
+ || state.active_addon_catalog.is_some())
{
SearchViewState::NoResults
} else {
@@ -236,10 +242,9 @@ fn render_search_state(
return;
}
- let mut card_width = area.width.min(64);
let query = crate::tui::text::truncate_width(
&state.search_query,
- card_width.saturating_sub(10) as usize,
+ area.width.min(64).saturating_sub(10) as usize,
);
let ctrl_p = crate::tui::text::CTRL_P_STR;
@@ -299,7 +304,8 @@ fn render_search_state(
}
}
SearchViewState::NoResults => {
- let symbol = if state.basic_terminal { "-" } else { "·" };
+ let provider_label = state.active_provider.label();
+ let next_provider = state.next_provider();
let msg = if let Some(preset) = state.active_browse_preset {
format!("No items found for {}", preset.label())
} else if let Some(catalog) = &state.active_addon_catalog {
@@ -311,66 +317,48 @@ fn render_search_state(
{
"No favorites saved yet".to_string()
} else if !state.search_query.trim().is_empty() {
- format!("No matches for “{query}”")
+ format!("No results for “{query}” on {provider_label}")
} else {
"No results found".to_string()
};
- lines.push(Line::from(vec![
- Span::styled(format!("{symbol} "), theme.text_dim),
- Span::styled(msg, theme.text.add_modifier(Modifier::BOLD)),
- ]));
+ lines.push(Line::from(vec![Span::styled(
+ msg,
+ theme.text.add_modifier(Modifier::BOLD),
+ )]));
lines.push(Line::from(""));
let pills = if state.is_tv_mode {
vec![
- Span::styled("[", theme.text_dim),
- Span::styled("/tv", theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Playlists", theme.subtext1),
- Span::styled(bullet, theme.text_dim),
- Span::styled("[", theme.text_dim),
+ Span::styled("[ Reload Playlists (", theme.subtext1),
Span::styled("r", theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Reload Playlist", theme.subtext1),
- Span::styled(bullet, theme.text_dim),
- Span::styled("[", theme.text_dim),
+ Span::styled(") ]", theme.subtext1),
+ Span::raw(" "),
+ Span::styled("[ Clear Search (", theme.subtext1),
Span::styled("c", theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Clear", theme.subtext1),
+ Span::styled(") ]", theme.subtext1),
]
} else if state.is_addon_mode {
vec![
- Span::styled("[", theme.text_dim),
+ Span::styled("[ Addon Manager (", theme.subtext1),
Span::styled(ctrl_p, theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Change Catalog", theme.subtext1),
- Span::styled(bullet, theme.text_dim),
- Span::styled("[", theme.text_dim),
- Span::styled("/addons", theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Manage Addons", theme.subtext1),
- Span::styled(bullet, theme.text_dim),
- Span::styled("[", theme.text_dim),
+ Span::styled(") ]", theme.subtext1),
+ Span::raw(" "),
+ Span::styled("[ Clear Search (", theme.subtext1),
Span::styled("c", theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Clear", theme.subtext1),
+ Span::styled(") ]", theme.subtext1),
]
} else {
vec![
- Span::styled("[", theme.text_dim),
+ Span::styled(
+ format!("[ Try on {} (", next_provider.label()),
+ theme.subtext1,
+ ),
Span::styled(ctrl_p, theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Switch Provider", theme.subtext1),
- Span::styled(bullet, theme.text_dim),
- Span::styled("[", theme.text_dim),
- Span::styled("/browse", theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Categories", theme.subtext1),
- Span::styled(bullet, theme.text_dim),
- Span::styled("[", theme.text_dim),
+ Span::styled(") ]", theme.subtext1),
+ Span::raw(" "),
+ Span::styled("[ Clear Search (", theme.subtext1),
Span::styled("c", theme.shortcut),
- Span::styled("] ", theme.text_dim),
- Span::styled("Clear", theme.subtext1),
+ Span::styled(") ]", theme.subtext1),
]
};
@@ -385,7 +373,7 @@ fn render_search_state(
"Search request failed"
}
});
- let wrap_width = card_width.saturating_sub(8).max(10) as usize;
+ let wrap_width = area.width.min(72).saturating_sub(8).max(10) as usize;
let wrapped_err_lines = crate::tui::text::wrap_text(err_text, wrap_width);
lines.push(Line::from(vec![
@@ -426,50 +414,36 @@ fn render_search_state(
_ => return,
};
- let max_line_width = lines.iter().map(|l| l.width()).max().unwrap_or(0) as u16;
- if matches!(view, SearchViewState::Error | SearchViewState::NoResults) {
- card_width = (max_line_width + 4)
- .clamp(32, area.width.saturating_sub(2))
- .min(72);
- } else if view == SearchViewState::Loading {
- card_width = (max_line_width + 2)
- .clamp(24, area.width.saturating_sub(2))
- .min(64);
- }
-
- let is_boxed = matches!(view, SearchViewState::Error | SearchViewState::NoResults);
+ let is_boxed = view == SearchViewState::Error;
let card_height = if is_boxed {
- (lines.len() as u16 + 2).min(area.height)
+ (lines.len() as u16 + 4).min(area.height)
} else {
- (lines.len() as u16).min(area.height)
+ lines.len() as u16
+ };
+ let card_y = if is_boxed {
+ area.y + area.height.saturating_sub(card_height) / 2
+ } else {
+ area.y + area.height.saturating_sub(card_height) / 3
};
let card = Rect {
- x: area.x + area.width.saturating_sub(card_width) / 2,
- y: area.y + area.height.saturating_sub(card_height) / 2,
- width: card_width,
+ x: area.x,
+ y: card_y,
+ width: area.width,
height: card_height,
};
if is_boxed && card.height >= 3 {
- let (border_style, title_text, title_style) = if view == SearchViewState::Error {
- (
- theme.error,
- " Error ",
- theme.error.add_modifier(Modifier::BOLD),
- )
- } else {
- (
- theme.muted,
- " No Results ",
- theme.subtext1.add_modifier(Modifier::BOLD),
- )
- };
+ let (border_style, title_text, title_style) = (
+ theme.error,
+ " Error ",
+ theme.error.add_modifier(Modifier::BOLD),
+ );
let block = Block::default()
.borders(Borders::ALL)
.border_type(crate::tui::overlay::border_type(state.basic_terminal))
.border_style(border_style)
.title(Line::from(vec![Span::styled(title_text, title_style)]))
- .padding(ratatui::widgets::Padding::horizontal(1));
+ .padding(ratatui::widgets::Padding::new(2, 2, 1, 1));
frame.render_widget(
Paragraph::new(lines)
.block(block)
@@ -477,14 +451,45 @@ fn render_search_state(
card,
);
} else {
- let alignment = if matches!(view, SearchViewState::Error | SearchViewState::NoResults) {
- Alignment::Left
- } else {
- Alignment::Center
- };
- frame.render_widget(Paragraph::new(lines).alignment(alignment), card);
+ frame.render_widget(Paragraph::new(lines).alignment(Alignment::Center), card);
}
}
+
+pub(crate) fn no_results_button_hitboxes(
+ area: Rect,
+ next_provider_label: &str,
+ ctrl_p: &str,
+ is_tv_mode: bool,
+ is_addon_mode: bool,
+) -> (Rect, Rect) {
+ let btn1_w = if is_tv_mode {
+ 24
+ } else if is_addon_mode {
+ 19 + ctrl_p.len() as u16
+ } else {
+ (14 + next_provider_label.len() + ctrl_p.len()) as u16
+ };
+ let btn2_w = 20;
+ let sep_w = 8;
+ let total_w = btn1_w + sep_w + btn2_w;
+ let start_x = area.x + area.width.saturating_sub(total_w) / 2;
+ let card_y = area.y + area.height.saturating_sub(3) / 3;
+ let btn_y = card_y + 2;
+
+ let btn1 = Rect {
+ x: start_x,
+ y: btn_y,
+ width: btn1_w,
+ height: 1,
+ };
+ let btn2 = Rect {
+ x: start_x + btn1_w + sep_w,
+ y: btn_y,
+ width: btn2_w,
+ height: 1,
+ };
+ (btn1, btn2)
+}
pub(crate) fn render_favorites_landing(
frame: &mut Frame,
area: Rect,
@@ -643,6 +648,82 @@ pub(crate) fn render_favorites_landing(
}
}
+pub(crate) fn render_discover_landing(
+ frame: &mut Frame,
+ area: Rect,
+ state: &AppState,
+ theme: &Theme,
+) {
+ if area.height < 3 || area.width < 20 {
+ return;
+ }
+
+ let presets = [
+ ("Trending Movies", "/browse · Popular & In-Theaters"),
+ ("Top Rated Series", "/browse · Award-Winning TV"),
+ ("New Releases", "/browse · Latest 4K & HD Additions"),
+ ("Curated Catalogs", "/browse · Explore Genres"),
+ ];
+
+ let card_width = search_deck_width(area, state, true);
+ let row_count = presets.len() as u16;
+ let content_height = (row_count + 2).min(area.height);
+
+ let card_area = Rect {
+ x: area.x + area.width.saturating_sub(card_width) / 2,
+ y: area.y,
+ width: card_width,
+ height: content_height,
+ };
+
+ let (bar, compass) = if state.basic_terminal {
+ ("-", "*")
+ } else {
+ ("─", "✦")
+ };
+ let block = Block::default()
+ .title(format!("{bar} {compass} Discover & Quick Categories "))
+ .title_style(theme.subtext1)
+ .borders(Borders::ALL)
+ .border_type(crate::tui::overlay::border_type(state.basic_terminal))
+ .border_style(theme.surface1);
+
+ frame.render_widget(block, card_area);
+
+ let inner_area = card_area.inner(Margin {
+ vertical: 1,
+ horizontal: 1,
+ });
+ if inner_area.height == 0 || inner_area.width == 0 {
+ return;
+ }
+
+ for (curr_y, (title, desc)) in (inner_area.y..inner_area.bottom()).zip(presets) {
+ let pointer = if state.basic_terminal { " - " } else { " · " };
+ let tag_len = crate::tui::text::width(desc);
+ let title_w = crate::tui::text::width(title);
+ let margins_len = 4;
+ let pad_len = (inner_area.width as usize).saturating_sub(margins_len + title_w + tag_len);
+
+ let line = Line::from(vec![
+ Span::raw(" "),
+ Span::styled(pointer, theme.accent),
+ Span::styled(title, theme.text.add_modifier(Modifier::BOLD)),
+ Span::raw(" ".repeat(pad_len)),
+ Span::styled(desc, theme.text_dim),
+ Span::raw(" "),
+ ]);
+
+ let row_area = Rect {
+ x: inner_area.x,
+ y: curr_y,
+ width: inner_area.width,
+ height: 1,
+ };
+ frame.render_widget(Paragraph::new(line), row_area);
+ }
+}
+
pub(crate) fn dynamic_search_placeholder(state: &AppState) -> &'static str {
if state.is_tv_mode {
const TV_HINTS: &[&str] = &[
@@ -818,6 +899,8 @@ fn render_search_bar(
} else if !is_query_empty {
if is_ultra_compact {
("[Enter]".to_string(), theme.accent)
+ } else if view == SearchViewState::NoResults {
+ ("[0 results]".to_string(), theme.text_dim)
} else {
("[Enter] Search".to_string(), theme.accent)
}
@@ -1011,6 +1094,8 @@ fn render_search_bar(
} else {
Some(format!("Item {} of {}", selected_num, total))
}
+ } else if view == SearchViewState::NoResults {
+ Some("0 results".to_string())
} else {
None
};
@@ -1122,6 +1207,106 @@ fn render_search_bar(
}
}
+fn home_bottom_bar_spans(
+ state: &AppState,
+ theme: &Theme,
+ width: u16,
+ modal_active: bool,
+) -> Vec<Span<'static>> {
+ let compact_tabs = width < 76;
+ let ultra_compact_tabs = width < 58;
+
+ let ctrl_s = if ultra_compact_tabs || compact_tabs {
+ "S"
+ } else {
+ crate::tui::text::CTRL_S_STR
+ };
+ let ctrl_t = if ultra_compact_tabs || compact_tabs {
+ "T"
+ } else {
+ crate::tui::text::CTRL_T_STR
+ };
+ let ctrl_a = if ultra_compact_tabs || compact_tabs {
+ "A"
+ } else {
+ crate::tui::text::CTRL_A_STR
+ };
+
+ let current_mode = state.mode();
+ let mut bar_spans: Vec<Span<'static>> = Vec::new();
+ let shortcut_style = if modal_active {
+ theme.muted
+ } else {
+ theme.shortcut
+ };
+ let bracket_style = if modal_active {
+ theme.muted
+ } else {
+ theme.text_dim
+ };
+ let text_style = if modal_active {
+ theme.muted
+ } else {
+ theme.text_dim
+ };
+
+ let sep = if state.basic_terminal {
+ " - "
+ } else if compact_tabs {
+ " · "
+ } else {
+ " · "
+ };
+
+ if state.streaming_enabled && current_mode != crate::tui::state::AppMode::Streaming {
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled(ctrl_s, shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ bar_spans.push(Span::styled("Stream", text_style));
+ }
+
+ if state.tv_enabled && current_mode != crate::tui::state::AppMode::Tv {
+ if !bar_spans.is_empty() {
+ bar_spans.push(Span::raw(sep));
+ }
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled(ctrl_t, shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ bar_spans.push(Span::styled("TV", text_style));
+ }
+
+ if state.addons_enabled && current_mode != crate::tui::state::AppMode::Addon {
+ if !bar_spans.is_empty() {
+ bar_spans.push(Span::raw(sep));
+ }
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled(ctrl_a, shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ bar_spans.push(Span::styled("Addon", text_style));
+ }
+
+ if !bar_spans.is_empty() {
+ let util_gap = if compact_tabs { " " } else { " " };
+ bar_spans.push(Span::raw(util_gap));
+ }
+
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled("?", shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ if !ultra_compact_tabs {
+ bar_spans.push(Span::styled("Help", text_style));
+ bar_spans.push(Span::raw(" "));
+ }
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled("q", shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ if !ultra_compact_tabs {
+ bar_spans.push(Span::styled("Quit", text_style));
+ }
+
+ bar_spans
+}
+
pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme) {
let is_actively_typing =
state.last_search_edit.elapsed() < std::time::Duration::from_millis(500);
@@ -1231,98 +1416,10 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if state.favorites_landing_visible() && !state.tv_config_popup {
render_favorites_landing(frame, vertical_chunks[rows.favorites], state, theme);
+ } else if !state.is_tv_mode && !state.tv_config_popup && area.height >= 26 {
+ render_discover_landing(frame, vertical_chunks[rows.favorites], state, theme);
}
- let compact_tabs = area.width < 76;
- let ultra_compact_tabs = area.width < 58;
-
- let ctrl_s = if ultra_compact_tabs || compact_tabs {
- "S"
- } else {
- crate::tui::text::CTRL_S_STR
- };
- let ctrl_t = if ultra_compact_tabs || compact_tabs {
- "T"
- } else {
- crate::tui::text::CTRL_T_STR
- };
- let ctrl_a = if ultra_compact_tabs || compact_tabs {
- "A"
- } else {
- crate::tui::text::CTRL_A_STR
- };
-
- let current_mode = state.mode();
- let mut bar_spans: Vec<Span> = Vec::new();
- let shortcut_style = if modal_active {
- theme.muted
- } else {
- theme.shortcut
- };
- let bracket_style = if modal_active {
- theme.muted
- } else {
- theme.text_dim
- };
- let text_style = if modal_active {
- theme.muted
- } else {
- theme.text_dim
- };
-
- let sep = if state.basic_terminal {
- " - "
- } else if compact_tabs {
- " · "
- } else {
- " · "
- };
-
- if state.streaming_enabled && current_mode != crate::tui::state::AppMode::Streaming {
- bar_spans.push(Span::styled("[", bracket_style));
- bar_spans.push(Span::styled(ctrl_s, shortcut_style));
- bar_spans.push(Span::styled("] ", bracket_style));
- bar_spans.push(Span::styled("Stream", text_style));
- }
-
- if state.tv_enabled && current_mode != crate::tui::state::AppMode::Tv {
- if !bar_spans.is_empty() {
- bar_spans.push(Span::raw(sep));
- }
- bar_spans.push(Span::styled("[", bracket_style));
- bar_spans.push(Span::styled(ctrl_t, shortcut_style));
- bar_spans.push(Span::styled("] ", bracket_style));
- bar_spans.push(Span::styled("TV", text_style));
- }
-
- if state.addons_enabled && current_mode != crate::tui::state::AppMode::Addon {
- if !bar_spans.is_empty() {
- bar_spans.push(Span::raw(sep));
- }
- bar_spans.push(Span::styled("[", bracket_style));
- bar_spans.push(Span::styled(ctrl_a, shortcut_style));
- bar_spans.push(Span::styled("] ", bracket_style));
- bar_spans.push(Span::styled("Addon", text_style));
- }
-
- if !bar_spans.is_empty() {
- let util_gap = if compact_tabs { " " } else { " " };
- bar_spans.push(Span::raw(util_gap));
- }
-
- bar_spans.push(Span::styled("[", bracket_style));
- bar_spans.push(Span::styled("?", shortcut_style));
- bar_spans.push(Span::styled("] ", bracket_style));
- if !ultra_compact_tabs {
- bar_spans.push(Span::styled("Help", text_style));
- bar_spans.push(Span::raw(" "));
- }
- bar_spans.push(Span::styled("[", bracket_style));
- bar_spans.push(Span::styled("q", shortcut_style));
- bar_spans.push(Span::styled("] ", bracket_style));
- if !ultra_compact_tabs {
- bar_spans.push(Span::styled("Quit", text_style));
- }
-
+ let bar_spans = home_bottom_bar_spans(state, theme, area.width, modal_active);
let bottom_bar_area = vertical_chunks[rows.mode_row];
frame.render_widget(
Paragraph::new(Line::from(bar_spans)).alignment(Alignment::Center),
@@ -1334,36 +1431,15 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
return;
}
- let has_results = !state.search_results.is_empty();
- let suggestion_height =
- if state.input_mode == InputMode::Editing && !state.search_suggestions.is_empty() {
- state.search_suggestions.len().min(6) as u16 + 3
- } else {
- 0
- };
- let chunks = if has_results {
- Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(1),
- Constraint::Length(1),
- Constraint::Min(0),
- ])
- .split(area)
- } else {
- Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(1),
- Constraint::Length(1),
- Constraint::Length(suggestion_height),
- Constraint::Length(0),
- Constraint::Min(0),
- ])
- .split(area)
- };
-
- let results_chunk = if has_results { chunks[2] } else { chunks[4] };
+ 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),
@@ -1378,7 +1454,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
show_cursor,
false,
);
-
let list_block = Block::default();
if !state.search_results.is_empty() {
let poster_width = if state.image_supported {
@@ -1828,7 +1903,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
state.basic_terminal,
);
} else {
- render_search_state(frame, chunks[4], state, theme, view);
+ render_search_state(frame, results_chunk, state, theme, view);
}
}
@@ -3049,4 +3124,68 @@ mod tests {
assert!(addon_rendered.contains("[Addons"));
assert!(addon_rendered.contains("Search movies and series via addons…"));
}
+
+ #[test]
+ fn test_search_view_state_loading_before_settle() {
+ let mut state = AppState {
+ input_mode: InputMode::Normal,
+ is_loading: false,
+ has_search_settled: false,
+ search_results: vec![],
+ ..Default::default()
+ };
+ state.search_query.set_content("Inception");
+
+ assert_eq!(search_view_state(&state), SearchViewState::Loading);
+
+ state.has_search_settled = true;
+ assert_eq!(search_view_state(&state), SearchViewState::NoResults);
+
+ state.search_results.push(crate::models::SearchResult {
+ id: "1".to_string(),
+ title: "Inception".to_string(),
+ stype: 1,
+ release_year: "2010".to_string(),
+ provider: crate::models::ProviderKind::MovieBox,
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ });
+ assert_eq!(search_view_state(&state), SearchViewState::Results);
+ }
+
+ #[test]
+ fn test_no_results_screen_layout_and_elements() {
+ let backend = TestBackend::new(100, 30);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let mut state = AppState {
+ input_mode: InputMode::Normal,
+ is_loading: false,
+ has_search_settled: true,
+ search_results: vec![],
+ ..Default::default()
+ };
+ state.search_query.set_content("deewaniyat");
+ 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();
+ let content = buffer
+ .content()
+ .iter()
+ .map(|cell| cell.symbol())
+ .collect::<String>();
+
+ assert!(content.contains("deewaniyat"));
+ assert!(content.contains("0 results"));
+ assert!(content.contains("No results for “deewaniyat” on MovieBox"));
+ assert!(content.contains("Try on 4KHDHub"));
+ assert!(content.contains("Clear Search"));
+ }
}
diff --git a/src/tui/state.rs b/src/tui/state.rs
index ee6ce02..7067fed 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -185,6 +185,7 @@ pub struct PlaybackState {
pub default_player: Option<String>,
pub available_players: Vec<PlayerKind>,
pub pending_play_link: Option<String>,
+ pub pending_playback_source: Option<crate::providers::models::PlaybackSource>,
pub pending_open_with: bool,
}
@@ -310,6 +311,8 @@ pub struct AppState {
pub default_player: Option<String>,
pub is_loading: bool,
pub is_resolving_playback: bool,
+ pub has_streams_settled: bool,
+ pub has_search_settled: bool,
pub is_playing: bool,
pub last_playback_launch: std::time::Instant,
pub status_message: String,
@@ -340,6 +343,7 @@ pub struct AppState {
pub subtitle_list: Vec<(String, String)>,
pub subtitle_list_state: ListState,
pub pending_play_link: Option<String>,
+ pub pending_playback_source: Option<crate::providers::models::PlaybackSource>,
pub pending_open_with: bool,
pub basic_terminal: bool,
pub bdix_enabled: bool,
@@ -472,6 +476,8 @@ impl Default for AppState {
dirty: true,
is_loading: false,
is_resolving_playback: false,
+ has_streams_settled: false,
+ has_search_settled: false,
is_playing: false,
last_playback_launch: std::time::Instant::now()
.checked_sub(std::time::Duration::from_secs(5))
@@ -502,6 +508,7 @@ impl Default for AppState {
subtitle_list: Vec::new(),
subtitle_list_state: ListState::default(),
pending_play_link: None,
+ pending_playback_source: None,
pending_open_with: false,
bdix_enabled: false,
streaming_enabled: true,
@@ -585,6 +592,21 @@ impl AppState {
.unwrap_or(self.active_provider)
}
+ pub fn next_provider(&self) -> ProviderKind {
+ let available_providers: Vec<ProviderKind> = crate::models::ProviderKind::ENABLED
+ .into_iter()
+ .filter(|p| !p.is_bdix() || self.bdix_enabled)
+ .collect();
+ if available_providers.is_empty() {
+ return self.active_provider;
+ }
+ let current = available_providers
+ .iter()
+ .position(|provider| *provider == self.active_provider)
+ .unwrap_or(0);
+ available_providers[(current + 1) % available_providers.len()]
+ }
+
pub fn notify(
&mut self,
kind: crate::tui::overlay::NotificationKind,
@@ -746,6 +768,7 @@ impl AppState {
self.is_homepage_mode = false;
self.favorites_focus = false;
self.favorites_landing_state.select(None);
+ self.has_search_settled = false;
}
pub fn clear_details_state(&mut self) {
@@ -764,6 +787,7 @@ impl AppState {
self.resource_list_state.select(None);
self.language_list_state.select(None);
self.details_pane = DetailsPane::Streams;
+ self.has_streams_settled = false;
}
pub fn favorites_available(&self) -> bool {
diff --git a/src/tui/theme.rs b/src/tui/theme.rs
index 666080f..d2a5fd8 100644
--- a/src/tui/theme.rs
+++ b/src/tui/theme.rs
@@ -148,6 +148,8 @@ pub(crate) fn classify_terminal(colorterm: &str, term: &str, term_program: &str)
|| term.contains("truecolor")
|| term.contains("kitty")
|| term.contains("ghostty")
+ || term.starts_with("foot")
+ || term.contains("alacritty")
|| std::env::var("WT_SESSION").is_ok()
|| term_program == "iTerm.app"
|| term_program == "Hyper"
@@ -968,6 +970,11 @@ mod tests {
classify_terminal("", "xterm-256color", "ghostty"),
ColorSupport::Truecolor
);
+ assert_eq!(classify_terminal("", "foot", ""), ColorSupport::Truecolor);
+ assert_eq!(
+ classify_terminal("", "alacritty", ""),
+ ColorSupport::Truecolor
+ );
assert_eq!(
classify_terminal("", "xterm-256color", ""),
ColorSupport::Color256
diff --git a/src/tui/widgets/badge.rs b/src/tui/widgets/badge.rs
index 1f760d4..cccde96 100644
--- a/src/tui/widgets/badge.rs
+++ b/src/tui/widgets/badge.rs
@@ -12,6 +12,7 @@ fn theme_color(style: Style, fallback: Color) -> Color {
pub fn resolution_label(resolution: i64) -> &'static str {
match resolution {
+ -1 => "Multi",
2160 | 4320 => "4K",
1080 => "1080p",
720 => "720p",
@@ -29,6 +30,7 @@ pub fn resolution_badge_spans<'a>(
) -> Vec<Span<'a>> {
if basic_terminal {
let (label, style) = match resolution {
+ -1 => ("[Multi]", theme.lavender.add_modifier(Modifier::BOLD)),
2160 | 4320 => ("[4K]", theme.rating.add_modifier(Modifier::BOLD)),
1080 => ("[1080p]", theme.highlight.add_modifier(Modifier::BOLD)),
720 => ("[720p]", theme.teal.add_modifier(Modifier::BOLD)),
@@ -41,6 +43,15 @@ 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
+ } else {
+ theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ },
+ " Multi ",
+ ),
2160 | 4320 => (
theme_color(theme.rating, Color::Rgb(249, 226, 175)),
if theme.is_light {
@@ -343,6 +354,7 @@ mod tests {
#[test]
fn test_resolution_label() {
+ assert_eq!(resolution_label(-1), "Multi");
assert_eq!(resolution_label(4320), "4K");
assert_eq!(resolution_label(2160), "4K");
assert_eq!(resolution_label(1080), "1080p");
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index 28ea20b..a909e9e 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -774,6 +774,7 @@ async fn test_no_results_and_error_state_rendering_hints() {
// No results view
app.state_mut().active_screen = Screen::Home;
app.state_mut().input_mode = InputMode::Normal;
+ app.state_mut().has_search_settled = true;
app.state_mut()
.set_mode(moviebox_tui::tui::state::AppMode::Streaming);
app.state_mut().active_provider = moviebox_tui::providers::models::ProviderKind::MovieBox;
@@ -784,10 +785,9 @@ async fn test_no_results_and_error_state_rendering_hints() {
terminal.draw(|frame| app.draw(frame)).unwrap();
let content = terminal.backend().buffer().content();
let text: String = content.iter().map(|c| c.symbol()).collect();
- assert!(text.contains("Switch Provider"));
- assert!(text.contains("Categories"));
- assert!(text.contains("Clear"));
-
+ assert!(text.contains("No results for “nonexistent_movie_xyz” on MovieBox"));
+ assert!(text.contains("Try on 4KHDHub"));
+ assert!(text.contains("Clear Search"));
// Error view
app.state_mut().search_error =
Some("Failed to connect to MovieBox provider: connection refused by server".to_string());