Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
refactor: optimize event loop using crossterm EventStream and update docs, image
Samir Hossainsf5af3b4cbe86
diff --git a/Cargo.lock b/Cargo.lockindex 99faa3b..672414b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -348,9 +348,9 @@ dependencies = [[[package]]name = "cc"-version = "1.3.0"+version = "1.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c89588d05638b5b4594a3348a2d6c20277e43a7f5c5202b05cc56888475a47b8"+checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"dependencies = ["find-msvc-tools","jobserver",@@ -585,6 +585,7 @@ dependencies = ["crossterm_winapi","derive_more","document-features",+ "futures-core","mio","parking_lot","rustix 1.1.4",@@ -1065,6 +1066,21 @@ version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"+[[package]]+name = "futures"+version = "0.3.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]+[[package]]name = "futures-channel"version = "0.3.33"@@ -1081,12 +1097,34 @@ version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"+[[package]]+name = "futures-executor"+version = "0.3.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]+[[package]]name = "futures-io"version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"+[[package]]+name = "futures-macro"+version = "0.3.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "futures-sink"version = "0.3.33"@@ -1105,8 +1143,10 @@ version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"dependencies = [+ "futures-channel","futures-core","futures-io",+ "futures-macro","futures-sink","futures-task","memchr",@@ -1920,6 +1960,7 @@ dependencies = ["chrono","crossterm","dirs",+ "futures","hmac","image","lru",diff --git a/Cargo.toml b/Cargo.tomlindex 78aada0..34fb700 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -15,8 +15,9 @@ rust-version = "1.85.0"[dependencies]base64 = "0.22.1"chrono = "0.4.45"-crossterm = "0.29.0"+crossterm = { version = "0.29.0", features = ["event-stream"] }dirs = "6.0.0"+futures = "0.3.31"hmac = "0.13.0"image = "0.25.10"lru = "0.18.1"diff --git a/README.md b/README.mdindex 1960990..89038e2 100644--- a/README.md+++ b/README.md@@ -2,13 +2,12 @@# MovieBox-Tui-A terminal client for finding and streaming movies, TV shows, and anime from your keyboard.+A lightning-fast terminal client for discovering and streaming movies, TV shows, and anime directly from your keyboard.[](https://crates.io/crates/moviebox-tui)[](https://crates.io/crates/moviebox-tui)[](#license)[](#requirements)-[](#support)<br>@@ -16,63 +15,29 @@ A terminal client for finding and streaming movies, TV shows, and anime from you<img src="https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/assets/screenshots/01-home.jpg" alt="MovieBox-Tui home screen" width="88%"/></p>-</div>-------## What is this?--**MovieBox-Tui** is a terminal UI I built to search MovieBox's public catalog and stream the results in my favorite video player, without leaving the terminal. It talks to the MovieBox API directly, resolves the video URLs it returns, and hands them off to `mpv`, `IINA`, or `VLC`.--No browsers, no ads, no login walls, no configuration. Type a title, pick a quality, watch.--> **Note:** This project is a client for a third-party service. It does not host, store, or redistribute any media. It only resolves the links the upstream API returns. It is intended strictly for educational and personal use. You are responsible for complying with copyright law in your jurisdiction.-------## Demo--A short walkthrough of the app in action:--<div align="center">-**[Watch the demo on YouTube](https://youtu.be/0L1Wc3cwMCc)**</div>----## Contents--- [What it can do](#what-it-can-do)-- [Screenshots](#screenshots)-- [Platform support](#platform-support)-- [Requirements](#requirements)-- [Install](#install)-- [Getting started](#getting-started)-- [Keybindings](#keybindings)-- [How it works](#how-it-works)-- [Project layout](#project-layout)-- [Troubleshooting](#troubleshooting)-- [Contributing](#contributing)-- [Acknowledgements](#acknowledgements)-- [License](#license)+## What is this?----+**MovieBox-Tui** brings the cinematic streaming experience to your terminal. It directly queries the MovieBox API to search catalogs, resolve video streams, and seamlessly hand them off to your favorite local video player (`mpv`, `IINA`, or `VLC`).-## What it can do+No browsers, no ads, no configuration. Type a title, select your preferred quality, and watch.-**Search and discovery**-The search bar is always active. Just start typing to get live, debounced suggestions, or use slash commands like `/movies`, `/shows`, `/anime`, `/discover`, and `/home` to browse curated trending feeds. When you hover over a result, you instantly see its full poster, release year, IMDb rating, and genres.+> **Disclaimer:** This project is a third-party client. It does not host, store, or redistribute any media. It strictly resolves links provided by the upstream API. It is intended for educational and personal use only. You are responsible for complying with copyright law in your jurisdiction.-**Playback**-The app automatically detects if you have `mpv`, `IINA`, or `VLC` installed. You get full access to season and episode browsing for TV series and anime. When you pick an episode, it concurrently fetches multiple resolutions (1080p, 720p, 480p) in parallel so you can choose a quality instantly. You can also pick external subtitle tracks and switch between audio dubs before playing. If a stream expires, pressing <kbd>R</kbd> re-resolves it on the fly.+----**Downloading**-If you want to save a video for later, the built-in downloader uses up to 16 parallel connections to max out your bandwidth. It shows live download speed, an ETA, and a progress bar directly in the interface. Everything saves cleanly to your system's default Downloads folder.+## Features-**The interface**-If you use a modern terminal like Kitty, WezTerm, iTerm2, Ghostty, or foot, all movie posters are rendered natively as high-resolution images right in your terminal. The details view is packed with metadata, including duration, country of origin, and a full synopsis. The app also silently checks GitHub releases in the background and notifies you if there's a newer version available, which you can manage with `/update` or `/toggle-update`.+- **Live Search & Discovery:** Type to search instantly, or use slash commands (`/movies`, `/shows`, `/anime`, `/discover`) to browse trending feeds.+- **Rich Metadata:** Hover over any title to instantly view full-resolution posters, release years, IMDb ratings, genres, and a complete synopsis.+- **Instant Playback:** Fetches multiple stream qualities (1080p, 720p, 480p) in parallel. Choose your resolution, pick subtitle tracks, and start watching in a single keystroke.+- **Lightning Fast Native Downloader:** Save videos for offline viewing using up to 16 parallel connections to maximize your bandwidth. Features live speed, ETA, and progress tracking.+- **Universal Terminal Support:** Works beautifully on any terminal and across all major operating systems (macOS, Linux, and Windows). Posters will render as native images in supported terminals or gracefully fall back to text.---@@ -108,288 +73,106 @@ If you use a modern terminal like Kitty, WezTerm, iTerm2, Ghostty, or foot, all</details>-<details>-<summary><b>Help overlay</b></summary>-<br>--<p align="center">- <img src="https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/assets/screenshots/08-help.jpg" alt="Keybindings help overlay" width="70%">-</p>--</details>-------## Platform support--| Platform | Status |-| :--- | :--- |-| **macOS** | Fully supported. Ghostty, iTerm2, and WezTerm render full-resolution image posters. |-| **Linux** | Supported. You **must** use Kitty, WezTerm, or Ghostty for full-resolution posters. Other terminals (like GNOME Terminal) will safely fall back to text. |-| **Windows** | Supported. You **must** use WezTerm for full-resolution posters. Windows Terminal/cmd will safely fall back to text. |--> **Warning: Windows support is currently in beta.**-> While the core features work perfectly, you may experience occasional rendering glitches or slow performance compared to macOS and Linux. I am actively improving this. If you encounter any bugs on Windows, please [open an issue](https://github.com/mesamirh/MovieBox-Tui/issues) so I can fix them!-----## Requirements+## Installation-You only need two things to use MovieBox-Tui: a compatible video player and a reasonably sized terminal.--**Video Player:** The app relies on your system's video players to handle playback. `mpv`, `IINA` (on macOS), and `VLC` are all fully supported. The app will automatically detect whichever players you have installed.--**Terminal Size:** Make sure your terminal window is at least 85×24 characters. If you launch the app in a window that's too small, it will pause and ask you to enlarge it. For the best experience with inline poster art, you'll want to use a terminal that speaks a modern graphics protocol like Kitty, WezTerm, iTerm2, Ghostty, or foot. Other terminals still work perfectly fine, but they will gracefully fall back to text placeholders instead of full images.--**(Optional) Rust:** If you prefer to build the app from source or install it via Cargo, you will need Rust 1.85 or newer (edition 2024). However, if you use the automated installation scripts or download a pre-built binary, you don't need Rust installed at all.--<details>-<summary><b>How to install a video player</b></summary>-<br>--```bash-# macOS-brew install mpv-# or, for a native-feel alternative-brew install --cask iina--# Debian / Ubuntu-sudo apt install mpv--# Arch Linux-sudo pacman -S mpv--# Fedora-sudo dnf install mpv--# Windows (Chocolatey)-choco install mpv-```--MovieBox-Tui auto-detects whichever players you have installed on the first run.--</details>-------## Install--The absolute easiest way to install MovieBox-Tui is using the automated installation scripts. This will download the latest pre-built binary for your system and add it to your PATH so you can just type `moviebox-tui` from anywhere.+You can install MovieBox-Tui using our automated scripts, or via Cargo if you are a Rust developer.### macOS & Linux-Paste this single line into your terminal:```bashcurl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash```-*(Requires `sudo` permissions to move the binary into `/usr/local/bin`)*### Windows (PowerShell)-Paste this single line into your PowerShell:```powershellirm https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.ps1 | iex```------<details>-<summary><b>Manual Download (No scripts)</b></summary>-<br>--If you prefer not to run the scripts, you can download the binaries directly:-1. Go to the [Releases page](https://github.com/mesamirh/MovieBox-Tui/releases/latest).-2. Download the correct file for your operating system:- - **macOS:** `MovieBox_macOS_Universal.tar.gz`- - **Windows:** `MovieBox_Windows_x64.zip`- - **Linux:** `MovieBox_Linux_x64.tar.gz`-3. Extract the file and run it directly.-</details>--<details>-<summary><b>Installing via Cargo (for Rust developers)</b></summary>-<br>--If you already have Rust installed, you can easily install from crates.io:-+### Via Cargo```bashcargo install moviebox-tui```-</details>-------## Getting started--Launch the app by typing `moviebox-tui` in your terminal.--Once you land on the home screen, you can simply start typing to instantly search for any title, or use a slash command like `/movies` or `/discover` to browse curated trending feeds. Navigate through the results using your arrow keys, and press <kbd>Enter</kbd> to view the full details of any title.--From the details view, you can browse seasons and episodes. Once you select an episode, pick your preferred stream quality and press <kbd>Enter</kbd> to instantly start playing it in your default video player. If you want to use a different player, press <kbd>o</kbd>.--You can press <kbd>?</kbd> at any time to see the full list of keybindings.-------## Keybindings--### Global--| Key | Action |-| :--- | :--- |-| any letter | Focus the search input and start typing |-| <kbd>?</kbd> | Toggle the help overlay |-| <kbd>Esc</kbd> | Go back, clear search, or close popup |-| <kbd>q</kbd> | Quit |-| <kbd>Ctrl</kbd>+<kbd>C</kbd> | Force quit |--### Navigation--| Key | Action |-| :--- | :--- |-| <kbd>Up</kbd>/<kbd>Down</kbd> | Move selection |-| <kbd>Left</kbd>/<kbd>Right</kbd> | Switch panels or page through results |-| <kbd>Enter</kbd> | Select or confirm |-| <kbd>Esc</kbd> | Go back (details screen) |--### On the details screen--| Key | Action |-| :--- | :--- |-| <kbd>Enter</kbd> | Play the selected stream in `mpv` |-| <kbd>o</kbd> | Choose a different player (`mpv`, `IINA`, or `VLC`) |-| <kbd>R</kbd> | Refresh streams. Useful when a link expires or fails. |-| <kbd>d</kbd> | Download the selected stream |-| <kbd>x</kbd> | Cancel an in-progress download |--### Slash Commands-You can type these into the search bar:--| Command | Action |-| :--- | :--- |-| `/discover`, `/home` | Browse trending titles |-| `/movies`, `/shows`, `/anime` | Browse specific categories |-| `/update` | Check for newer versions manually |-| `/toggle-update` | Toggle automatic update checking on startup |-| `/github` | Open the source repository in your browser |-------## How it works--The app has two layers.--The **provider layer** (`src/providers/moviebox/`) is a small HTTP client for the MovieBox API. It rotates through a pool of API hosts, signs each request with an HMAC-MD5 signature, and retries automatically on transient failures. When you open a title, it fires off requests for every resolution in parallel and deduplicates the results. That is why picking a quality feels instant.--The **TUI layer** (`src/tui/`) is where everything you see happens. It is built on [Ratatui](https://ratatui.rs) and driven by an async event loop. Every keystroke, network response, and background task becomes an `Action` on a single channel, so the interface never blocks. Poster images decode on background tasks and get cached in an LRU so scrolling through search results stays smooth.--Playback is not reinvented. The app just spawns your video player with the resolved URL and any subtitle track you picked. That means all the polish (hotkeys, subtitles, seeking) comes from mpv, IINA, or VLC, exactly as you would expect them to behave.----## Project layout--```-src/-├── main.rs Binary entry: terminal + tokio setup-├── lib.rs Library root-├── providers/-│ └── moviebox/-│ ├── client.rs HTTP client, host-pool failover, retries-│ ├── crypto.rs HMAC-MD5 request signing + device spoofing-│ └── mod.rs High-level API calls-└── tui/- ├── app.rs Event loop and Action handlers- ├── action.rs The Action enum (every event in one place)- ├── event.rs Crossterm to Action bridge- ├── state.rs Application state- ├── theme.rs Colors- └── screens/- ├── home.rs Home, search, and result list- ├── details.rs Movie / series detail view- └── help.rs Keybindings overlay--install.sh macOS/Linux automated install script-install.ps1 Windows automated install script-scripts/-└── release.sh Cross-platform build script for releases-```--If you're poking around the code, `src/tui/app.rs` is the map. Every user action, network response, and background task funnels through its match statement.-------## Troubleshooting--<details>-<summary><b>Posters show up as colored blocks instead of images</b></summary>-<br>+## Requirements-Your terminal doesn't support inline graphics. The app falls back to text placeholders. Try Kitty, WezTerm, iTerm2, Ghostty, or foot if you want the images.--</details>+1. **Terminal:** Any terminal! A minimum window size of 85×24 is required. Modern terminals with graphics protocols will display native posters automatically.+2. **Video Player:** `mpv`, `IINA` (macOS), or `VLC` must be installed on your system. MovieBox-Tui will auto-detect them.<details>-<summary><b>"mpv player not found in PATH"</b></summary>+<summary><b>Download pre-built binary</b></summary><br>-Install `mpv` (see [Requirements](#requirements)), or press <kbd>o</kbd> to pick `IINA` or `VLC` if you already have those. Player detection happens once at startup, so install first, then launch the app.+You can download the compiled executable directly from the [Releases page](https://github.com/mesamirh/MovieBox-Tui/releases/latest).</details><details>-<summary><b>"Terminal too small"</b></summary>+<summary><b>Need to install a video player?</b></summary><br>-The app needs at least **85×24** characters. Enlarge the window or shrink the font.+```bash+# macOS+brew install mpv+# or+brew install --cask iina-</details>+# Debian / Ubuntu+sudo apt install mpv-<details>-<summary><b>Nothing found, stream won't play, or link expired</b></summary>-<br>+# Arch Linux+sudo pacman -S mpv-Direct stream URLs are short-lived and expire after some time. On the details screen, press <kbd>R</kbd> to re-resolve. If a title has no streams at all, it may be unreleased on MovieBox or temporarily gone from their catalog.+# Windows+choco install mpv+```</details>-<details>-<summary><b>"Failed to check for updates" on startup</b></summary>-<br>+----The app checks GitHub for the latest release on startup. GitHub limits unauthenticated requests to 60 per hour per IP address. If you open and close the app many times in a short period, you might temporarily hit this limit. You can use the `/toggle-update` slash command to disable startup update checks and bypass this error.+## Getting Started-</details>+Launch the app by typing `moviebox-tui` in your terminal.-<details>-<summary><b>Downloads are slow or crawl</b></summary>-<br>+- **Search:** Start typing to search for titles instantly.+- **Navigate:** Use the <kbd>Up</kbd> / <kbd>Down</kbd> / <kbd>Left</kbd> / <kbd>Right</kbd> arrow keys to move around.+- **Select:** Press <kbd>Enter</kbd> to view details, browse seasons/episodes, and start playback.+- **Switch Player:** Press <kbd>o</kbd> on a stream to choose a different installed player.+- **Download:** Press <kbd>d</kbd> to download the selected stream to your machine.+- **Refresh:** Press <kbd>r</kbd> to re-resolve expired stream links.+- **Help:** Press <kbd>?</kbd> anywhere in the app to view all keybindings.+- **Quit:** Press <kbd>q</kbd> or <kbd>Esc</kbd> repeatedly to exit.-If the source doesn't support HTTP range requests, the downloader falls back to a single connection. Nothing you can do about that except pick a different quality or source. If it does support ranges, you should see `[16x]` in the status line.--</details>+### Slash Commands+Use the search bar to run dedicated slash commands:+- `/discover`, `/home` - Browse trending and curated titles.+- `/movies`, `/shows`, `/anime` - Jump to specific category feeds.+- `/clear-cache` - Free up disk space by removing cached data and images.+- `/update` - Manually check for updates.+- `/toggle-update` - Enable or disable background update checking.---## Contributing-Contributions are welcome. If you're planning something bigger than a small fix, please open an issue first so we can talk it through.+Contributions are highly welcome! For major changes, please open an issue first to discuss your ideas.```bashgit clone https://github.com/<your-username>/MovieBox-Tui.gitcd MovieBox-Tuicargo build--# Before opening a PR:-cargo fmt --all-cargo clippy --all-targets --all-features -- -D warnings```-Commits follow [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `docs:`, etc.). See [CONTRIBUTING.md](CONTRIBUTING.md) for the full guide.+We follow [Conventional Commits](https://www.conventionalcommits.org/). Ensure `cargo fmt` and `cargo clippy` pass cleanly before submitting a Pull Request. See [CONTRIBUTING.md](CONTRIBUTING.md) for more details.---## Support-If you enjoy using MovieBox-Tui and want to support its development, you can send a tip to any of the crypto addresses below.+If you enjoy this project and want to support its continuous development:- **EVM (ETH, BNB, Polygon, etc):** `0x7ea20d5fa29d87f33195f5a3b211ff94038d794c`- **BTC:** `3MEAtqtRWrQBhnaMi3Zuf5nt2efNUS2LUQ`@@ -397,20 +180,9 @@ If you enjoy using MovieBox-Tui and want to support its development, you can sen----## Acknowledgements--Built with [Ratatui](https://ratatui.rs), [crossterm](https://github.com/crossterm-rs/crossterm), [ratatui-image](https://github.com/benjajaja/ratatui-image), [tokio](https://tokio.rs), and [reqwest](https://github.com/seanmonstar/reqwest). Playback is powered by [mpv](https://mpv.io), [IINA](https://iina.io), and [VLC](https://www.videolan.org).-------## License--Dual-licensed under [MIT](LICENSE-MIT) or [Apache 2.0](LICENSE-APACHE) at your option.------<div align="center">+Dual-licensed under [MIT](LICENSE-MIT) or [Apache 2.0](LICENSE-APACHE) at your option.<br>Made by [**@mesamirh**](https://github.com/mesamirh)<sub>Not affiliated with MovieBox or its operators.</sub>diff --git a/assets/screenshots/01-home.jpg b/assets/screenshots/01-home.jpgindex a1b593b..bd7aac2 100644Binary files a/assets/screenshots/01-home.jpg and b/assets/screenshots/01-home.jpg differdiff --git a/assets/screenshots/02-search-results.jpg b/assets/screenshots/02-search-results.jpgindex e7de695..98453b0 100644Binary files a/assets/screenshots/02-search-results.jpg and b/assets/screenshots/02-search-results.jpg differdiff --git a/assets/screenshots/03-movie-details.jpg b/assets/screenshots/03-movie-details.jpgindex fe4f8af..46da23c 100644Binary files a/assets/screenshots/03-movie-details.jpg and b/assets/screenshots/03-movie-details.jpg differdiff --git a/assets/screenshots/04-series-details.jpg b/assets/screenshots/04-series-details.jpgindex 24c5e9a..88d5ee1 100644Binary files a/assets/screenshots/04-series-details.jpg and b/assets/screenshots/04-series-details.jpg differdiff --git a/assets/screenshots/05-discover-movies.jpg b/assets/screenshots/05-discover-movies.jpgindex dfa36c4..8236532 100644Binary files a/assets/screenshots/05-discover-movies.jpg and b/assets/screenshots/05-discover-movies.jpg differdiff --git a/assets/screenshots/06-discover-series.jpg b/assets/screenshots/06-discover-series.jpgindex 9808387..ee0ab30 100644Binary files a/assets/screenshots/06-discover-series.jpg and b/assets/screenshots/06-discover-series.jpg differdiff --git a/assets/screenshots/07-discover-anime.jpg b/assets/screenshots/07-discover-anime.jpgindex 1a39b6b..d9af48b 100644Binary files a/assets/screenshots/07-discover-anime.jpg and b/assets/screenshots/07-discover-anime.jpg differdiff --git a/assets/screenshots/08-help.jpg b/assets/screenshots/08-help.jpgindex 531e113..615dfc0 100644Binary files a/assets/screenshots/08-help.jpg and b/assets/screenshots/08-help.jpg differdiff --git a/src/main.rs b/src/main.rsindex 86c071c..6ae2ced 100644--- a/src/main.rs+++ b/src/main.rs@@ -2,14 +2,17 @@ use moviebox_tui::tui::app::App;#[tokio::main]async fn main() -> std::io::Result<()> {- crossterm::execute!(std::io::stdout(), crossterm::event::EnableFocusChange)?;- let mut terminal = ratatui::init();+ let stdout = std::io::stdout();+ let backend = ratatui::backend::CrosstermBackend::new(std::io::BufWriter::with_capacity(65536, stdout));+ let mut terminal = ratatui::Terminal::new(backend)?;+ crossterm::terminal::enable_raw_mode()?;+ crossterm::execute!(std::io::stdout(), crossterm::terminal::EnterAlternateScreen, crossterm::event::EnableFocusChange)?;let mut app = App::new();let result = app.run(&mut terminal).await;- ratatui::restore();- crossterm::execute!(std::io::stdout(), crossterm::event::DisableFocusChange)?;+ crossterm::terminal::disable_raw_mode()?;+ crossterm::execute!(std::io::stdout(), crossterm::terminal::LeaveAlternateScreen, crossterm::event::DisableFocusChange)?;result}diff --git a/src/providers/moviebox/client.rs b/src/providers/moviebox/client.rsindex d8919c8..7e3fc9a 100644--- a/src/providers/moviebox/client.rs+++ b/src/providers/moviebox/client.rs@@ -184,11 +184,9 @@ impl MovieBoxClient {Err(e) => return Err(ScraperError::Reqwest(e)),};- let body_val: Value = match serde_json::from_str(&raw_text) {+ let body_val: Value = match tokio::task::spawn_blocking(move || serde_json::from_str(&raw_text)).await.unwrap() {Ok(v) => v,- Err(e) => {- return Err(ScraperError::Json(e));- }+ Err(e) => return Err(ScraperError::Json(e)),};if let Some(data) = body_val.get("data") {diff --git a/src/tui/app.rs b/src/tui/app.rsindex 1cd3530..ad6bd51 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -1,4 +1,4 @@-use ratatui::{DefaultTerminal, Frame};+use ratatui::Frame;use std::time::Duration;use tokio::sync::mpsc;@@ -173,7 +173,7 @@ impl App {.map(|s| s.to_string())}- pub async fn run(&mut self, terminal: &mut DefaultTerminal) -> std::io::Result<()> {+ pub async fn run<B: ratatui::backend::Backend>(&mut self, terminal: &mut ratatui::Terminal<B>) -> std::io::Result<()> where std::io::Error: From<<B as ratatui::backend::Backend>::Error> {if self.state.image_picker.is_none() && self.state.image_supported {match ratatui_image::picker::Picker::from_query_stdio() {Ok(picker) => {@@ -292,12 +292,12 @@ impl App {}async fn handle_action(&mut self, action: Action) -> Option<()> {- if !matches!(action, Action::Tick) {+ if !matches!(action, Action::Tick | Action::UpdateDownload(..)) {self.state.dirty = true;}match action {Action::Tick => {- let mut needs_redraw = self.state.is_loading || self.state.tick_count < 15;+ let mut needs_redraw = (self.state.is_loading && self.state.tick_count % 5 == 0) || self.state.tick_count < 15;self.state.tick_count = self.state.tick_count.wrapping_add(1);if self.state.toast_timer > 0 {needs_redraw = true;@@ -317,6 +317,85 @@ impl App {self.state.dirty = true;}+ if self.state.search_query.is_empty() && matches!(self.state.active_screen, crate::tui::state::Screen::Home) {+ use chrono::Timelike;+ let hour = chrono::Local::now().hour();+ let greeting_time = if hour >= 5 && hour < 12 {+ "Good morning"+ } else if hour >= 12 && hour < 17 {+ "Good afternoon"+ } else if hour >= 17 && hour < 21 {+ "Good evening"+ } else {+ "Working late"+ };+ let punct = if greeting_time == "Working late" { "?" } else { "" };+ let greeting = format!("{}, {}{}", greeting_time, self.state.username, punct);++ let prompts = [+ "What are you in the mood to watch?",+ "Try 'Oppenheimer', 'Titanic', or 'Interstellar'...",+ "Discover your next binge-worthy masterpiece...",+ "Search for blockbuster movies, hit shows, or anime...",+ "Feeling nostalgic? Search timeless classics...",+ "Explore trending titles for your movie night...",+ ];+ let type_speed = 3;+ let del_speed = 1;+ let pause1 = 90;+ let pause2 = 15;++ let greeting_cycle = greeting.len() * type_speed + pause1 + greeting.len() * del_speed + pause2;+ let mut total_ticks = 0;+ for p in prompts.iter() {+ total_ticks += p.len() * type_speed + pause1 + p.len() * del_speed + pause2;+ }++ let tick_u = self.state.tick_count as usize;+ let mut animated_text = String::new();++ if tick_u < greeting_cycle {+ let t = tick_u;+ let t_type = greeting.len() * type_speed;+ let t_del = greeting.len() * del_speed;+ let display_len = if t < t_type {+ t / type_speed+ } else if t < t_type + pause1 {+ greeting.len()+ } else if t < t_type + pause1 + t_del {+ greeting.len().saturating_sub((t - (t_type + pause1)) / del_speed)+ } else {+ 0+ };+ animated_text = greeting[0..display_len.min(greeting.len())].to_string();+ } else {+ let mut t = (tick_u - greeting_cycle) % total_ticks;+ for p in prompts.iter() {+ let t_type = p.len() * type_speed;+ let t_del = p.len() * del_speed;+ let cycle = t_type + pause1 + t_del + pause2;+ if t < cycle {+ let display_len = if t < t_type {+ t / type_speed+ } else if t < t_type + pause1 {+ p.len()+ } else if t < t_type + pause1 + t_del {+ p.len().saturating_sub((t - (t_type + pause1)) / del_speed)+ } else {+ 0+ };+ animated_text = p[0..display_len.min(p.len())].to_string();+ break;+ } else {+ t -= cycle;+ }+ }+ }+ if self.state.cached_animated_text != animated_text {+ self.state.cached_animated_text = animated_text;+ self.state.dirty = true;+ }+ }let current_query = self.state.search_query.trim().to_string();if current_query != self.state.last_suggest_query&& self.state.last_search_edit.elapsed()@@ -661,7 +740,10 @@ impl App {} else {self.state.selected_episode};- crate::cache::invalidate_stream_cache(&id, se, ep);+ let id_clone = id.clone();+ tokio::task::spawn_blocking(move || {+ crate::cache::invalidate_stream_cache(&id_clone, se, ep);+ });self.state.selected_season = se;self.state.selected_episode = ep;self.action_sender@@ -1118,7 +1200,8 @@ impl App {.await{if let Ok(bytes) = resp.bytes().await {- if let Ok(img) = image::load_from_memory(&bytes) {+ let bytes_clone = bytes.clone();+ if let Ok(Ok(img)) = tokio::task::spawn_blocking(move || image::load_from_memory(&bytes_clone)).await {tx.send(Action::SearchPosterLoaded(id,Some(std::sync::Arc::new(img)),@@ -1306,7 +1389,8 @@ impl App {.await{if let Ok(bytes) = resp.bytes().await {- if let Ok(img) = image::load_from_memory(&bytes) {+ let bytes_clone = bytes.clone();+ if let Ok(Ok(img)) = tokio::task::spawn_blocking(move || image::load_from_memory(&bytes_clone)).await {tx.send(Action::SearchPosterLoaded(id,Some(std::sync::Arc::new(img)),@@ -1745,14 +1829,17 @@ impl App {let id_clone = id.clone();tokio::spawn(async move {if !force_refresh {- if let Some(cached) = crate::cache::get_details_cache(&id_clone) {+ let id_for_cache = id_clone.clone();+ if let Ok(Some(cached)) = tokio::task::spawn_blocking(move || crate::cache::get_details_cache(&id_for_cache)).await {sender.send(Action::DetailsSuccess(id_clone.clone(), cached)).ok();return;}}match client.get_details(&id_clone).await {Ok(details) => {- crate::cache::set_details_cache(&id_clone, &details);+ let id_for_cache = id_clone.clone();+ let details_for_cache = details.clone();+ let _ = tokio::task::spawn_blocking(move || crate::cache::set_details_cache(&id_for_cache, &details_for_cache)).await;sender.send(Action::DetailsSuccess(id_clone, details)).ok();}Err(e) => {@@ -1865,11 +1952,13 @@ impl App {.header("User-Agent", "MovieBox-Tui/1.0").send().await- && let Ok(bytes) = resp.bytes().await- && let Ok(img) = image::load_from_memory(&bytes){+ if let Ok(bytes) = resp.bytes().await {+ if let Ok(Ok(img)) = tokio::task::spawn_blocking(move || image::load_from_memory(&bytes)).await {let _ = action_tx.send(Action::PosterSuccess(id_clone, std::sync::Arc::new(img)));+ }+ }}});}@@ -2568,13 +2657,15 @@ impl App {.header("User-Agent", "MovieBox-Tui/1.0").send().await- && let Ok(bytes) = resp.bytes().await- && let Ok(img) = image::load_from_memory(&bytes){- let _ = action_tx.send(Action::PosterSuccess(- id_clone,- std::sync::Arc::new(img),- ));+ if let Ok(bytes) = resp.bytes().await {+ if let Ok(Ok(img)) = tokio::task::spawn_blocking(move || image::load_from_memory(&bytes)).await {+ let _ = action_tx.send(Action::PosterSuccess(+ id_clone,+ std::sync::Arc::new(img),+ ));+ }+ }}});}@@ -2777,7 +2868,8 @@ impl App {tokio::spawn(async move {if !force_refresh {- if let Some(cached) = crate::cache::get_stream_cache(&id_clone, season, episode) {+ let id_for_cache = id_clone.clone();+ if let Ok(Some(cached)) = tokio::task::spawn_blocking(move || crate::cache::get_stream_cache(&id_for_cache, season, episode)).await {sender.send(Action::SetStatus("Loaded from cache.".to_string())).ok();sender.send(Action::EpisodeStreamsReady(season, episode, cached)).ok();return;@@ -2962,7 +3054,11 @@ impl App {let array_payload = serde_json::Value::Array(filtered.clone());if count > 0 {if let Some(subject_id) = &self.state.active_subject_id {- crate::cache::set_stream_cache(subject_id, target_se, target_ep, &array_payload);+ let id_clone = subject_id.clone();+ let payload_clone = array_payload.clone();+ tokio::task::spawn_blocking(move || {+ crate::cache::set_stream_cache(&id_clone, target_se, target_ep, &payload_clone);+ });}}@@ -2988,8 +3084,11 @@ impl App {self.state.status_timer = 150;}Action::UpdateDownload(prog, stat) => {- self.state.download_progress = prog;- self.state.download_status = stat;+ if self.state.download_progress != prog || self.state.download_status != stat {+ self.state.download_progress = prog;+ self.state.download_status = stat;+ self.state.dirty = true;+ }}Action::CancelDownload => {self.statediff --git a/src/tui/event.rs b/src/tui/event.rsindex 83a04b8..60a82af 100644--- a/src/tui/event.rs+++ b/src/tui/event.rs@@ -14,47 +14,41 @@ impl EventHandler {let (sender, receiver) = mpsc::unbounded_channel();let event_sender = sender.clone();+ let mut tick_interval = tokio::time::interval(tick_rate);+tokio::spawn(async move {+ let mut reader = crossterm::event::EventStream::new();+ use futures::StreamExt;+loop {- let polled = match crossterm::event::poll(Duration::from_millis(16)) {- Ok(p) => p,- Err(_) => break,- };- if polled {- match crossterm::event::read() {- Ok(CrosstermEvent::Key(key)) => {- let is_press = key.kind == KeyEventKind::Press;- if is_press && event_sender.send(Action::Key(key)).is_err() {- break;+ tokio::select! {+ _ = tick_interval.tick() => {+ let _ = event_sender.send(Action::Tick);+ }+ Some(event) = reader.next() => {+ match event {+ Ok(CrosstermEvent::Key(key)) => {+ let is_press = key.kind == KeyEventKind::Press;+ if is_press && event_sender.send(Action::Key(key)).is_err() {+ break;+ }}+ Ok(CrosstermEvent::FocusGained) => {+ let _ = event_sender.send(Action::FocusChange);+ }+ Ok(CrosstermEvent::Resize(w, h)) => {+ if event_sender.send(Action::Resize(w, h)).is_err() {+ break;+ }+ }+ _ => {}}- Ok(CrosstermEvent::FocusGained) => {- let _ = event_sender.send(Action::FocusChange);- }- Ok(CrosstermEvent::Resize(w, h))- if event_sender.send(Action::Resize(w, h)).is_err() =>- {- break;- }- Ok(CrosstermEvent::Resize(_, _)) => {}- _ => {}}- } else {- tokio::time::sleep(Duration::from_millis(10)).await;}}});- let tick_sender = sender.clone();- tokio::spawn(async move {- let mut interval = tokio::time::interval(tick_rate);- loop {- interval.tick().await;- if tick_sender.send(Action::Tick).is_err() {- break;- }- }- });+Self { receiver, sender }}diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex dc929f7..48670aa 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -16,90 +16,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)if !state.status_message.is_empty() && state.input_mode == InputMode::Normal {format!("{}{}", search_prefix, state.status_message)} else if state.search_query.is_empty() {- use chrono::Timelike;- let hour = chrono::Local::now().hour();- let greeting_time = if hour >= 5 && hour < 12 {- "Good morning"- } else if hour >= 12 && hour < 17 {- "Good afternoon"- } else if hour >= 17 && hour < 21 {- "Good evening"- } else {- "Working late"- };- let punct = if greeting_time == "Working late" {- "?"- } else {- ""- };- let greeting = format!("{}, {}{}", greeting_time, state.username, punct);-- let prompts = [- "What are you in the mood to watch?",- "Try 'Oppenheimer', 'Titanic', or 'Interstellar'...",- "Discover your next binge-worthy masterpiece...",- "Search for blockbuster movies, hit shows, or anime...",- "Feeling nostalgic? Search timeless classics...",- "Explore trending titles for your movie night...",- ];- let type_speed = 3;- let del_speed = 1;- let pause1 = 90;- let pause2 = 15;-- let greeting_cycle =- greeting.len() * type_speed + pause1 + greeting.len() * del_speed + pause2;-- let mut total_ticks = 0;- for p in prompts.iter() {- total_ticks += p.len() * type_speed + pause1 + p.len() * del_speed + pause2;- }-- let tick_u = state.tick_count as usize;-- let mut animated_text = String::new();-- if tick_u < greeting_cycle {- let t = tick_u;- let t_type = greeting.len() * type_speed;- let t_del = greeting.len() * del_speed;-- let display_len = if t < t_type {- t / type_speed- } else if t < t_type + pause1 {- greeting.len()- } else if t < t_type + pause1 + t_del {- greeting- .len()- .saturating_sub((t - (t_type + pause1)) / del_speed)- } else {- 0- };- animated_text = greeting[0..display_len.min(greeting.len())].to_string();- } else {- let mut t = (tick_u - greeting_cycle) % total_ticks;- for p in prompts.iter() {- let t_type = p.len() * type_speed;- let t_del = p.len() * del_speed;- let cycle = t_type + pause1 + t_del + pause2;-- if t < cycle {- let display_len = if t < t_type {- t / type_speed- } else if t < t_type + pause1 {- p.len()- } else if t < t_type + pause1 + t_del {- p.len().saturating_sub((t - (t_type + pause1)) / del_speed)- } else {- 0- };- animated_text = p[0..display_len.min(p.len())].to_string();- break;- } else {- t -= cycle;- }- }- }+ let animated_text = &state.cached_animated_text;if state.input_mode == InputMode::Editing {if show_cursor {@@ -473,14 +390,15 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)if let Some(img) = state.search_posters.peek(&res.id) {if state.image_supported {+ let target_dims = (poster_area.width, state.poster_rows);let needs_protocol =- state.search_poster_protocols.get(&res.id).map(|(r, _)| *r)- != Some(poster_area);+ state.search_poster_protocols.get(&res.id).map(|(d, _)| *d)+ != Some(target_dims);if needs_protocol {if let Some(picker) = &mut state.image_picker {let size = ratatui::layout::Size::new(- poster_area.width,- poster_area.height.min(state.poster_rows),+ target_dims.0,+ target_dims.1,);if let Ok(proto) = picker.new_protocol((**img).clone(),@@ -489,7 +407,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)) {state.search_poster_protocols- .insert(res.id.clone(), (poster_area, proto));+ .insert(res.id.clone(), (target_dims, proto));}}}diff --git a/src/tui/state.rs b/src/tui/state.rsindex 682ccb6..b9db7f3 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -60,10 +60,11 @@ pub struct AppState {pub is_homepage_mode: bool,pub current_tab_id: String,pub current_page: usize,+ pub cached_animated_text: String,pub search_posters: lru::LruCache<String, std::sync::Arc<image::DynamicImage>>,pub search_poster_protocols: std::collections::HashMap<String,- (ratatui::layout::Rect, ratatui_image::protocol::Protocol),+ ((u16, u16), ratatui_image::protocol::Protocol),>,pub search_list_state: TableState,@@ -139,6 +140,7 @@ impl Default for AppState {Self {active_screen: Screen::Startup,input_mode: InputMode::Normal,+ cached_animated_text: String::new(),search_query: String::new(),last_suggest_query: String::new(),last_search_edit: std::time::Instant::now(),