Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(player): resilient android intent fallback and zero-copy titles
Samir Hossains48b033af2753
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5d55b36..1a64ecf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,12 @@- **Dependency Advisory Remediation**:- Updated `rustls` to `0.23.45` and `rustls-webpki` to `0.103.15`, resolving security advisory `RUSTSEC-2026-0285` (TLS 1.3 handshake boundary handling).+### Performance+- **TUI Landing Frame Latency & Allocation Pruning**:+ - Reduced landing frame draw latency from 28.95 µs to 23.03 µs (-20.4%) by eliminating per-frame heap allocations (`logo_text: &'static str`, zero-copy `&rows.rects` borrowing) and caching search result metrics across unscrollable viewports.+- **Zero-Copy Title Normalization (`clean_moviebox_title`)**:+ - Converted `clean_moviebox_title` from an allocating `String` generator to a pure zero-copy slice parser (`&str -> &str`), replacing allocating `.to_lowercase()` substring searches with in-place ASCII case-insensitive matching (`rfind_ignore_ascii_case`).+ - Achieved sub-microsecond parsing latency: 191.43 ns/op over 10,000 operations with zero heap allocations.### Changed- **Concise Error and Status Messaging**:- Streamlined `ProviderError::user_message` to output compact, high-signal status messages under 40 characters for mobile and compact viewports.@@ -24,6 +30,14 @@- Compacted addon torrent stream warning to `Blocked {} torrent streams. HTTP only.`.- Streamlined player crash fallback diagnostic to `Player exited (code {code}).`.### Fixed+- **Terminal Color Support Environment Isolation**:+ - Scoped process environment lookups (`ALACRITTY_WINDOW_ID`, `WEZTERM_EXECUTABLE`, `TILIX_ID`, `VTE_VERSION`) strictly to `ColorSupport::current()` rather than the pure `classify_terminal` helper.+ - Eliminated host environment variable leakage where running tests inside Alacritty or WezTerm falsely forced 256-color and basic terminals to report Truecolor support.+ - Extracted pure `is_vte_version_truecolor` validator, eliminating non-thread-safe `std::env::set_var` test mutations.+- **Android Termux Intent Opener Resiliency & Socket Fallback**:+ - Implemented multi-opener resolution in `src/player.rs` returning ordered candidate commands (`termux-am` → `termux-open` → `termux-open-url`).+ - Added automatic in-flight fallback in `src/tui/app/playback.rs`: if `termux-am` exits with `am.sock` / socket connection failure on Android 12+, MovieBox-TUI automatically retries with `termux-open` without halting playback.+ - Replaced long and inaccurate `"Run: pkg install -y termux-am"` notifications with concise mobile-formatted messages under 32 characters (`Termux Setup: Run 'pkg install termux-tools'.`, `No Player: Install a video player.`, `CLI mpv: Switch to Android Player in /settings.`).- **tmux Poster Image Passthrough**:- Replaced the hard-coded `$TMUX` detection block in `src/tui/terminal.rs` with an outer terminal graphics capability probe (`GHOSTTY_RESOURCES_DIR`, `KITTY_WINDOW_ID`, `WEZTERM_EXECUTABLE`, `ITERM_SESSION_ID`, `ALACRITTY_LOG`, `ALACRITTY_WINDOW_ID`, `foot`).- Enabled automatic poster graphics queries and DCS passthrough inside `tmux` sessions running within Ghostty, Kitty, WezTerm, iTerm2, foot, and Alacritty, eliminating empty "No Art" placeholders.@@ -532,7 +546,7 @@### Removed- **Poster Graphics Configuration & Halfblocks Engine**:- Removed Unicode Halfblocks poster engine (`▀`/`▄`), eliminating low-resolution cell distortion, font scanlines, and terminal redraw lag during list scrolling.- - Removed redundant `Poster Graphics` toggle from Settings Hub (`/settings` $\to$ Appearance) and `config.json`, delegating terminal graphics strictly to automatic native GPU protocol detection (Kitty, Sixel, iTerm2).+ - Removed redundant `Poster Graphics` toggle from Settings Hub (`/settings` → Appearance) and `config.json`, delegating terminal graphics strictly to automatic native GPU protocol detection (Kitty, Sixel, iTerm2).### Fixed- **Cross-Platform Handle Safety & Silent Failure Elimination**:@@ -572,7 +586,7 @@- Streamlined `/config` as a direct alias for `/settings`.- **Pruned Redundant Theme Slash Command**:- - Removed standalone `/theme` slash command, parser routing, and auto-suggestions; theme selection and visual palette swatches are managed directly within the interactive Settings Hub (`/settings` $\to$ Appearance $\to$ Theme).+ - Removed standalone `/theme` slash command, parser routing, and auto-suggestions; theme selection and visual palette swatches are managed directly within the interactive Settings Hub (`/settings` → Appearance → Theme).- **Discover Categories Landing Card UX**:- **Clean Segmented Landing Deck Header Styling**:- Replaced crowded decorative star (`★`) and bracket (`[ ]`) glyphs with a clean, segmented tab bar header (`Continue Watching │ Favorites (Tab)`).diff --git a/docs/cross-platform.md b/docs/cross-platform.mdindex 94e106f..4924932 100644--- a/docs/cross-platform.md+++ b/docs/cross-platform.md@@ -13,7 +13,7 @@ the release checks in [`release-checklist.md`](release-checklist.md).| macOS | IINA preferred player (via the installed IINA `iina-cli`); VLC/mpv `.app` paths detected. `process_group(0)` on spawn. || Windows | mpv/VLC detected via Program Files + `%LOCALAPPDATA%` (filtering out 0-byte Windows Store `WindowsApps` execution alias stubs); path-safe file stems; static MSVC CRT linking (`+crt-static`) for zero-dependency standalone binaries; handle-safe atomic download replacement (dropping file handles before renames); background process spawning (registry queries and yt-dlp downloader) hardened with `CREATE_NO_WINDOW` (`0x08000000`) and isolated with `CREATE_NEW_PROCESS_GROUP` (`0x00000200`) so terminal interrupts do not kill active downloads; updater helper process spawned with `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` so console exit does not abort in-flight binary replacement; full legacy Windows console (`conhost.exe` on Windows 8.1 and earlier) compatibility via crossterm WinAPI fallback by eliminating unsupported underline color sequences. || Linux | Flatpak mpv/VLC supported (`flatpak run …`); xdg data/cache dirs. Linux ARM64 binaries (`MovieBox_Linux_arm64.tar.gz`) are fully static musl executables linked with 64KB ELF segment alignment (`-Wl,-z,max-page-size=65536`) for compatibility across 4KB, 16KB, and 64KB page kernels. |-| Android (Termux) | Targets `aarch64-linux-android` linked against the Android NDK (Clang API 24+) and system Bionic `libc.so`, producing a native ELF executable with a valid `PT_PHDR` program header table and `/system/bin/linker64` dynamic loader. This eliminates `Could not find a PHDR: broken executable?` crashes and executes natively without on-device compilation. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution. Android playback delegates to external video players via Termux intent dispatchers (`termux-open`, `termux-open-url`, `termux-am`), requiring `pkg install -y termux-tools termux-am`. Detection prioritizes the native Android player bridge ahead of headless CLI players and strictly gates system `am` probes behind `target_os = "android"`. Download storage directory prefers `~/storage/downloads` when running inside verified Termux environments. |+| Android (Termux) | Targets `aarch64-linux-android` linked against the Android NDK (Clang API 24+) and system Bionic `libc.so`, producing a native ELF executable with a valid `PT_PHDR` program header table and `/system/bin/linker64` dynamic loader. This eliminates `Could not find a PHDR: broken executable?` crashes and executes natively without on-device compilation. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution. Android playback delegates to external video players via Termux intent dispatchers (`termux-open`, `termux-open-url`, `termux-am`), requiring `pkg install -y termux-tools`. Detection prioritizes the native Android player bridge ahead of headless CLI players, automatically falls back from `termux-am` to `termux-open` if `am.sock` is unavailable, and strictly gates system `am` probes behind `target_os = "android"`. Download storage directory prefers `~/storage/downloads` when running inside verified Termux environments. |## Terminal capabilitiesdiff --git a/docs/known-issues.md b/docs/known-issues.mdindex 58b6c5c..53e4fe4 100644--- a/docs/known-issues.md+++ b/docs/known-issues.md@@ -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 400+ unit and integration tests across 11 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 447 unit and integration tests across 12 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/players.md b/docs/players.mdindex e6cf1e8..2f25554 100644--- a/docs/players.md+++ b/docs/players.md@@ -69,11 +69,11 @@ On Android (Termux), terminal sessions do not have access to an X11 or Wayland d- **Command-Line `mpv` (`pkg install mpv`)**: Operates in headless/audio-only mode. Video output cannot be rendered to the terminal screen and will fail or produce audio without video.- **External Player Intent Dispatch**: Video playback is designed to open in dedicated Android video player applications (**VLC for Android**, **Just Player**, **MX Player**, or **MPV Android APK**).-- **Prerequisites**: Termux requires `pkg install -y termux-tools termux-am`.- - `termux-open` (from `termux-tools`) broadcasts an `android.intent.action.VIEW` intent to `TermuxOpenReceiver`, presenting Android's native app chooser.- - `termux-am` (from `termux-am`) connects directly to `termux-app`'s local Unix domain socket (`am.sock`), allowing intent parameter passing (including `User-Agent`, `Referer`, and subtitles).-- **Actionable Mobile Diagnostics**: MovieBox-TUI parses intent dispatcher output and failure status codes, surfacing compact, player-neutral diagnostics formatted for mobile viewports:- - **Missing video player app**: Surfaces `No Video Player` (`Install a video player on Android.`).- - **Missing intent bridge / socket**: Surfaces `Termux Setup Needed` (`Run: pkg install -y termux-am`).- - **Headless CLI mpv**: Detects video output initialization failures and surfaces `CLI mpv Unsupported` (`Switch to Android Player in /settings.`).+- **Prerequisites**: Termux requires `pkg install -y termux-tools`.+ - `termux-open` (from `termux-tools`) broadcasts an `android.intent.action.VIEW` intent to `TermuxOpenReceiver`, presenting Android's native app chooser without relying on background sockets.+ - `termux-am` (from `termux-am`) attempts to connect to `am.sock` to pass custom stream headers and subtitles. If `am.sock` is unavailable or socket connection fails, MovieBox-TUI automatically falls back to `termux-open` transparently.+- **Actionable Mobile Diagnostics**: MovieBox-TUI parses intent dispatcher output and failure status codes, surfacing compact diagnostics formatted for mobile viewports:+ - **Missing video player app**: Surfaces `No Player` (`Install a video player.`).+ - **Missing intent tools**: Surfaces `Termux Setup` (`Run 'pkg install termux-tools'.`).+ - **Headless CLI mpv**: Detects video output initialization failures and surfaces `CLI mpv` (`Switch to Android Player in /settings.`).- **SELinux & Exit Code 126 Protection**: On Android 10+, executing `/system/bin/am` directly from an unrooted Termux environment causes Android's system shell to call `cmd activity`, which is blocked by SELinux when executing Termux app data binaries (`Permission denied`, exit code 126). MovieBox-TUI detects Termux environments, prevents illegal system `am` invocations, preserves `LD_PRELOAD` for Termux applet compatibility, strictly gates system `am` checks behind `target_os = "android"` (preventing GNU Automake collisions on desktop Linux), and surfaces actionable remediation notifications.diff --git a/docs/testing.md b/docs/testing.mdindex b4e0b42..deaffbe 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 **400+ automated tests across 10 test suites** (294 unit tests in `src/lib.rs` and 125+ integration tests across 10 focused suites in `tests/`), running fully offline by default without mocking or live network dependencies.+The test suite comprises **447 automated tests across 12 test suites** (320 unit tests in `src/lib.rs` and 127 integration tests across 10 focused 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:```textdiff --git a/install.sh b/install.shindex 22e051f..784f429 100755--- a/install.sh+++ b/install.sh@@ -668,7 +668,7 @@ printf " %b•%b %bBinary:%b %b%s%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_REif [ -n "$PLAYER_DETECTED" ]; thenprintf " %b•%b %bPlayer:%b %b%s (ready)%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_GREEN" "$PLAYER_DETECTED" "$C_RESET"elif [ "$IS_TERMUX" -eq 1 ]; then- printf " %b•%b %bPlayer:%b %bNone detected (run 'pkg install -y termux-tools termux-am')%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_SAPPHIRE" "$C_RESET"+ printf " %b•%b %bPlayer:%b %bNone detected (run 'pkg install -y termux-tools')%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_SAPPHIRE" "$C_RESET"elseprintf " %b•%b %bPlayer:%b %bNone detected (mpv, VLC, or IINA recommended)%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_SAPPHIRE" "$C_RESET"fi@@ -683,7 +683,7 @@ printf " %b$ moviebox-tui%b\n\n" "$C_GREEN" "$C_RESET"if [ -z "$PLAYER_DETECTED" ]; thenif [ "$IS_TERMUX" -eq 1 ]; then- printf " %bℹ%b Note: Run %b'pkg install -y termux-tools termux-am'%b to enable video playback on Termux.\n" "$C_SAPPHIRE" "$C_RESET" "$C_BOLD" "$C_RESET"+ printf " %bℹ%b Note: Run %b'pkg install -y termux-tools'%b to enable video playback on Termux.\n" "$C_SAPPHIRE" "$C_RESET" "$C_BOLD" "$C_RESET"printf " Streams play via external Android players (VLC, MX Player, or Just Player).\n\n"elseprintf " %bℹ%b Note: A media player (mpv, VLC, or IINA) is recommended for video playback.\n\n" "$C_SAPPHIRE" "$C_RESET"diff --git a/src/favorites.rs b/src/favorites.rsindex feebbf6..7dfb748 100644--- a/src/favorites.rs+++ b/src/favorites.rs@@ -19,7 +19,7 @@ impl FavoriteItem {let title = if title.trim().is_empty() {details.title.clone()} else {- title+ title.to_string()};let stype = if details.is_series() { 2 } else { 1 };let release_year = details.year.clone().unwrap_or_default();diff --git a/src/history.rs b/src/history.rsindex 14ae683..aadcfed 100644--- a/src/history.rs+++ b/src/history.rs@@ -33,7 +33,7 @@ impl WatchHistoryItem {let title = if title.trim().is_empty() {details.title.clone()} else {- title+ title.to_string()};let stype = if details.is_series() { 2 } else { 1 };let release_year = details.year.clone().unwrap_or_default();@@ -382,7 +382,7 @@ impl HistoryManager {if let Some(t) = title {let clean_i = crate::providers::moviebox::clean_moviebox_title(&i.title);let clean_t = crate::providers::moviebox::clean_moviebox_title(t);- if !clean_i.is_empty() && clean_i.eq_ignore_ascii_case(&clean_t) {+ if !clean_i.is_empty() && clean_i.eq_ignore_ascii_case(clean_t) {if i.stype == 1 {return true;}diff --git a/src/models.rs b/src/models.rsindex adc28fd..66515df 100644--- a/src/models.rs+++ b/src/models.rs@@ -42,7 +42,7 @@ impl<'a> SubjectIdentity<'a> {let clean_a = crate::providers::moviebox::clean_moviebox_title(self.title);let clean_b = crate::providers::moviebox::clean_moviebox_title(other.title);- if !clean_a.is_empty() && clean_a.eq_ignore_ascii_case(&clean_b) {+ if !clean_a.is_empty() && clean_a.eq_ignore_ascii_case(clean_b) {let year_a = self.release_year.trim();let year_b = other.release_year.trim();if !year_a.is_empty() && !year_b.is_empty() {diff --git a/src/player.rs b/src/player.rsindex 6a88430..8f2a8ff 100644--- a/src/player.rs+++ b/src/player.rs@@ -57,7 +57,7 @@ pub fn detect() -> Vec<PlayerKind> {let mut players = Vec::new();let is_termux = crate::updater::artifact::is_termux_environment();- if is_termux && android_opener().is_some() {+ if is_termux && !android_openers().is_empty() {players.push(PlayerKind::AndroidIntent);}@@ -74,7 +74,7 @@ pub fn detect() -> Vec<PlayerKind> {players.push(PlayerKind::Vlc);}- if !is_termux && android_opener().is_some() {+ if !is_termux && !android_openers().is_empty() {players.push(PlayerKind::AndroidIntent);}@@ -155,42 +155,58 @@ fn build_player_process_command(executable: &str) -> Command {}}-#[derive(Debug, Clone)]#[allow(clippy::enum_variant_names)]-enum AndroidOpener {+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum AndroidOpener {+ TermuxAm(String),TermuxOpen(String),TermuxOpenUrl(String),- TermuxAm(String),#[cfg(target_os = "android")]SystemAm(String),}-fn probe_android_opener() -> Option<AndroidOpener> {+pub fn probe_android_openers() -> Vec<AndroidOpener> {+ let mut openers = Vec::new();+if let Some(custom) = configured_executable("MOVIEBOX_ANDROID_PLAYER_PATH") {if custom.ends_with("termux-open-url") {- return Some(AndroidOpener::TermuxOpenUrl(custom));+ openers.push(AndroidOpener::TermuxOpenUrl(custom));} else if custom.ends_with("termux-am") {- return Some(AndroidOpener::TermuxAm(custom));+ openers.push(AndroidOpener::TermuxAm(custom));} else {- return Some(AndroidOpener::TermuxOpen(custom));+ openers.push(AndroidOpener::TermuxOpen(custom));}+ return openers;}+ let mut push_unique = |opener: AndroidOpener| {+ if !openers.iter().any(|existing| match (existing, &opener) {+ (AndroidOpener::TermuxAm(a), AndroidOpener::TermuxAm(b))+ | (AndroidOpener::TermuxOpen(a), AndroidOpener::TermuxOpen(b))+ | (AndroidOpener::TermuxOpenUrl(a), AndroidOpener::TermuxOpenUrl(b)) => a == b,+ #[cfg(target_os = "android")]+ (AndroidOpener::SystemAm(a), AndroidOpener::SystemAm(b)) => a == b,+ _ => false,+ }) {+ openers.push(opener);+ }+ };+#[cfg(target_os = "android")]let is_termux = crate::updater::artifact::is_termux_environment();if let Ok(prefix) = std::env::var("PREFIX") {let termux_am = format!("{prefix}/bin/termux-am");if Path::new(&termux_am).is_file() {- return Some(AndroidOpener::TermuxAm(termux_am));+ push_unique(AndroidOpener::TermuxAm(termux_am));}let termux_open = format!("{prefix}/bin/termux-open");if Path::new(&termux_open).is_file() {- return Some(AndroidOpener::TermuxOpen(termux_open));+ push_unique(AndroidOpener::TermuxOpen(termux_open));}let termux_open_url = format!("{prefix}/bin/termux-open-url");if Path::new(&termux_open_url).is_file() {- return Some(AndroidOpener::TermuxOpenUrl(termux_open_url));+ push_unique(AndroidOpener::TermuxOpenUrl(termux_open_url));}}@@ -199,63 +215,51 @@ fn probe_android_opener() -> Option<AndroidOpener> {crate::updater::artifact::TERMUX_PREFIX_USR);if Path::new(&termux_am_static).is_file() {- return Some(AndroidOpener::TermuxAm(termux_am_static));+ push_unique(AndroidOpener::TermuxAm(termux_am_static));}let termux_open_static = format!("{}/bin/termux-open",crate::updater::artifact::TERMUX_PREFIX_USR);if Path::new(&termux_open_static).is_file() {- return Some(AndroidOpener::TermuxOpen(termux_open_static));+ push_unique(AndroidOpener::TermuxOpen(termux_open_static));}let termux_open_url_static = format!("{}/bin/termux-open-url",crate::updater::artifact::TERMUX_PREFIX_USR);if Path::new(&termux_open_url_static).is_file() {- return Some(AndroidOpener::TermuxOpenUrl(termux_open_url_static));+ push_unique(AndroidOpener::TermuxOpenUrl(termux_open_url_static));}if let Some(path) = find_in_path("termux-am") {- return Some(AndroidOpener::TermuxAm(path));+ push_unique(AndroidOpener::TermuxAm(path));}if let Some(path) = find_in_path("termux-open") {- return Some(AndroidOpener::TermuxOpen(path));+ push_unique(AndroidOpener::TermuxOpen(path));}if let Some(path) = find_in_path("termux-open-url") {- return Some(AndroidOpener::TermuxOpenUrl(path));+ push_unique(AndroidOpener::TermuxOpenUrl(path));}+#[cfg(target_os = "android")]if !is_termux {let is_root = unsafe { libc::getuid() == 0 };if is_root {if Path::new("/system/bin/am").is_file() {- return Some(AndroidOpener::SystemAm("/system/bin/am".to_string()));+ push_unique(AndroidOpener::SystemAm("/system/bin/am".to_string()));}if let Some(path) = find_in_path("am") {- return Some(AndroidOpener::SystemAm(path));+ push_unique(AndroidOpener::SystemAm(path));}}}- None-}--fn android_opener() -> Option<AndroidOpener> {- static CACHED: std::sync::RwLock<Option<AndroidOpener>> = std::sync::RwLock::new(None);- if let Ok(guard) = CACHED.read() {- if let Some(opener) = &*guard {- return Some(opener.clone());- }- }+ openers+}- let detected = probe_android_opener();- if let Some(opener) = &detected {- if let Ok(mut guard) = CACHED.write() {- *guard = Some(opener.clone());- }- }- detected+pub fn android_openers() -> Vec<AndroidOpener> {+ probe_android_openers()}fn append_android_intent_extras(@@ -283,13 +287,14 @@ fn append_android_intent_extras(}}-fn android_intent_command(+pub fn android_intent_command_for_opener(+ opener: &AndroidOpener,url: &str,subtitle: Option<&str>,headers: &[(String, String)],) -> Command {- match android_opener() {- Some(AndroidOpener::TermuxOpen(path)) => {+ match opener {+ AndroidOpener::TermuxOpen(path) => {let mut cmd = Command::new(path);cmd.arg("--chooser").arg("--content-type")@@ -297,12 +302,12 @@ fn android_intent_command(.arg(url);cmd}- Some(AndroidOpener::TermuxOpenUrl(path)) => {+ AndroidOpener::TermuxOpenUrl(path) => {let mut cmd = Command::new(path);cmd.arg(url);cmd}- Some(AndroidOpener::TermuxAm(path)) => {+ AndroidOpener::TermuxAm(path) => {let mut cmd = Command::new(path);cmd.arg("start").arg("-a")@@ -315,7 +320,7 @@ fn android_intent_command(cmd}#[cfg(target_os = "android")]- Some(AndroidOpener::SystemAm(path)) => {+ AndroidOpener::SystemAm(path) => {let mut cmd = Command::new(path);cmd.arg("start").arg("--user")@@ -333,15 +338,50 @@ fn android_intent_command(cmd.env_remove("LD_PRELOAD");cmd}- None => {+ }+}++pub fn android_intent_commands(+ url: &str,+ subtitle: Option<&str>,+ headers: &[(String, String)],+) -> Vec<(AndroidOpener, Command)> {+ let openers = android_openers();+ if openers.is_empty() {+ let mut cmd = Command::new("termux-open");+ cmd.arg("--chooser")+ .arg("--content-type")+ .arg("video/*")+ .arg(url);+ return vec![(AndroidOpener::TermuxOpen("termux-open".to_string()), cmd)];+ }+ openers+ .into_iter()+ .map(|opener| {+ let cmd = android_intent_command_for_opener(&opener, url, subtitle, headers);+ (opener, cmd)+ })+ .collect()+}++fn android_intent_command(+ url: &str,+ subtitle: Option<&str>,+ headers: &[(String, String)],+) -> Command {+ let commands = android_intent_commands(url, subtitle, headers);+ commands+ .into_iter()+ .next()+ .map(|(_, cmd)| cmd)+ .unwrap_or_else(|| {let mut cmd = Command::new("termux-open");cmd.arg("--chooser").arg("--content-type").arg("video/*").arg(url);cmd- }- }+ })}fn mpv_command(@@ -1459,6 +1499,7 @@ mod tests {None,None,);+let args = cmd.get_args().map(|arg| arg.to_string_lossy().into_owned())@@ -1468,6 +1509,32 @@ mod tests {assert!(args.contains(&"--http-header-fields=Cookie: session=abc, token=123".to_string()));assert!(args.contains(&"--http-header-fields=Accept: text/html, */*".to_string()));}+ #[test]+ fn test_android_intent_commands_fallback_order() {+ let temp_dir =+ std::env::temp_dir().join(format!("termux_fallback_test_{}", std::process::id()));+ let bin_dir = temp_dir.join("bin");+ std::fs::create_dir_all(&bin_dir).unwrap();+ let termux_am = bin_dir.join("termux-am");+ let termux_open = bin_dir.join("termux-open");+ std::fs::write(&termux_am, "#!/bin/sh\nexit 0").unwrap();+ std::fs::write(&termux_open, "#!/bin/sh\nexit 0").unwrap();++ unsafe {+ std::env::set_var("TERMUX_VERSION", "0.118.0");+ std::env::set_var("PREFIX", temp_dir.to_str().unwrap());+ }+ let commands = android_intent_commands("https://example.test/stream.m3u8", None, &[]);+ unsafe {+ std::env::remove_var("TERMUX_VERSION");+ std::env::remove_var("PREFIX");+ }+ let _ = std::fs::remove_dir_all(&temp_dir);++ assert!(commands.len() >= 2);+ assert!(matches!(commands[0].0, AndroidOpener::TermuxAm(_)));+ assert!(matches!(commands[1].0, AndroidOpener::TermuxOpen(_)));+ }#[test]fn header_support_allows_android_cookies_and_vlc_proxy() {diff --git a/src/providers/moviebox/client.rs b/src/providers/moviebox/client.rsindex 9fcf220..af8638e 100644--- a/src/providers/moviebox/client.rs+++ b/src/providers/moviebox/client.rs@@ -89,7 +89,6 @@ impl MovieBoxClient {}pub async fn ensure_session(&self) -> Result<String, ScraperError> {- // Fast path: valid in-memory sessionif let Some(session) = self.session.read()@@ -101,7 +100,6 @@ impl MovieBoxClient {}}- // Cache path: valid persisted sessionif let Some(persisted) = load_persisted_session() {if persisted.is_valid() {let mut write_guard = self.session.write().unwrap_or_else(|e| e.into_inner());@@ -110,10 +108,8 @@ impl MovieBoxClient {}}- // Single-flight lock: serialize concurrent guest loginslet _guard = self.init_lock.lock().await;- // Double check after acquiring lockif let Some(session) = self.session.read()diff --git a/src/providers/moviebox/title.rs b/src/providers/moviebox/title.rsindex b829ee2..3c91827 100644--- a/src/providers/moviebox/title.rs+++ b/src/providers/moviebox/title.rs@@ -1,7 +1,7 @@-pub fn clean_moviebox_title(raw_title: &str) -> String {+pub fn clean_moviebox_title(raw_title: &str) -> &str {let mut title = raw_title.trim();if title.is_empty() {- return String::new();+ return "";}while title.starts_with('[') {@@ -39,40 +39,39 @@ pub fn clean_moviebox_title(raw_title: &str) -> String {}if let Some(pos) = title.rfind(" - ") {- let suffix = title[pos + 3..].to_lowercase();- let is_tag = suffix.contains("hindi")- || suffix.contains("tamil")- || suffix.contains("telugu")- || suffix.contains("kannada")- || suffix.contains("malayalam")- || suffix.contains("bengali")- || suffix.contains("marathi")- || suffix.contains("punjabi")- || suffix.contains("gujarati")- || suffix.contains("urdu")- || suffix.contains("english")- || suffix.contains("spanish")- || suffix.contains("french")- || suffix.contains("german")- || suffix.contains("italian")- || suffix.contains("japanese")- || suffix.contains("korean")- || suffix.contains("chinese")- || suffix.contains("russian")- || suffix.contains("portuguese")- || suffix.contains("turkish")- || suffix.contains("arabic")- || suffix.contains("dub")- || suffix.contains("audio")- || suffix.contains("multi")- || suffix.contains("season")- || (suffix.starts_with('s')+ let suffix = &title[pos + 3..];+ let is_tag = contains_ignore_ascii_case(suffix, "hindi")+ || contains_ignore_ascii_case(suffix, "tamil")+ || contains_ignore_ascii_case(suffix, "telugu")+ || contains_ignore_ascii_case(suffix, "kannada")+ || contains_ignore_ascii_case(suffix, "malayalam")+ || contains_ignore_ascii_case(suffix, "bengali")+ || contains_ignore_ascii_case(suffix, "marathi")+ || contains_ignore_ascii_case(suffix, "punjabi")+ || contains_ignore_ascii_case(suffix, "gujarati")+ || contains_ignore_ascii_case(suffix, "urdu")+ || contains_ignore_ascii_case(suffix, "english")+ || contains_ignore_ascii_case(suffix, "spanish")+ || contains_ignore_ascii_case(suffix, "french")+ || contains_ignore_ascii_case(suffix, "german")+ || contains_ignore_ascii_case(suffix, "italian")+ || contains_ignore_ascii_case(suffix, "japanese")+ || contains_ignore_ascii_case(suffix, "korean")+ || contains_ignore_ascii_case(suffix, "chinese")+ || contains_ignore_ascii_case(suffix, "russian")+ || contains_ignore_ascii_case(suffix, "portuguese")+ || contains_ignore_ascii_case(suffix, "turkish")+ || contains_ignore_ascii_case(suffix, "arabic")+ || contains_ignore_ascii_case(suffix, "dub")+ || contains_ignore_ascii_case(suffix, "audio")+ || contains_ignore_ascii_case(suffix, "multi")+ || contains_ignore_ascii_case(suffix, "season")+ || (suffix.chars().next().is_some_and(|c| c == 's' || c == 'S')&& suffix[1..].chars().all(|c| c.is_ascii_digit() || c == '-'));if is_tag {title = title[..pos].trim();}}-if let Some(s_idx) = title.rfind(" S") {let suffix = &title[s_idx + 2..];let is_season = suffix@@ -83,7 +82,7 @@ pub fn clean_moviebox_title(raw_title: &str) -> String {}}- if let Some(s_idx) = title.to_lowercase().rfind(" season ") {+ if let Some(s_idx) = rfind_ignore_ascii_case(title, " season ") {title = title[..s_idx].trim();}@@ -103,18 +102,36 @@ pub fn clean_moviebox_title(raw_title: &str) -> String {}}}- let cleaned = title- .trim_end_matches(['-', ':', '_', '.', ' '])- .trim()- .to_string();+ let cleaned = title.trim_end_matches(['-', ':', '_', '.', ' ']).trim();if cleaned.is_empty() {- raw_title.trim().to_string()+ raw_title.trim()} else {cleaned}}+fn rfind_ignore_ascii_case(haystack: &str, needle: &str) -> Option<usize> {+ if needle.is_empty() {+ return Some(haystack.len());+ }+ if haystack.len() < needle.len() {+ return None;+ }+ let h = haystack.as_bytes();+ let n = needle.as_bytes();+ for i in (0..=h.len() - n.len()).rev() {+ if h[i..i + n.len()].eq_ignore_ascii_case(n) {+ return Some(i);+ }+ }+ None+}++fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {+ rfind_ignore_ascii_case(haystack, needle).is_some()+}+pub fn language_to_code(name: &str) -> Option<&'static str> {let lower = name.trim().to_lowercase();match lower.as_str() {diff --git a/src/tui/app/download.rs b/src/tui/app/download.rsindex 44ed4a2..dfbb0d5 100644--- a/src/tui/app/download.rs+++ b/src/tui/app/download.rs@@ -49,7 +49,7 @@ impl App {|| !self.state.available_seasons.is_empty();let season = self.state.selected_season;let episode = self.state.selected_episode;- let safe_title = crate::download::safe_file_stem(&clean_title);+ let safe_title = crate::download::safe_file_stem(clean_title);let extension = link.split('?')@@ -683,7 +683,7 @@ impl App {.map(|details| details.title.as_str()).unwrap_or(crate::download::DEFAULT_STREAM_NAME);let clean_title = crate::providers::moviebox::clean_moviebox_title(raw_title);- let safe_title = crate::download::safe_file_stem(&clean_title);+ let safe_title = crate::download::safe_file_stem(clean_title);let base_dir = self.resolve_download_base_dir();let target_dir = base_dirdiff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex dedf5b3..e9f1967 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -130,7 +130,7 @@ impl App {self.state.is_resolving_playback = false;self.state.pending_playback_source = None;let message = if crate::updater::artifact::is_termux_environment() {- "Install player intent tools: 'pkg install -y termux-tools termux-am' and ensure an Android player (VLC, MX Player, or Just Player) is installed."+ "Run 'pkg install termux-tools' and install an Android video player."} else {"Install mpv, IINA, or VLC to enable video playback."};@@ -380,7 +380,29 @@ impl App {(link.clone(), local_subtitle.clone())};- let mut command = crate::tui::player::command(+ let spawn_configured_command =+ |mut cmd: std::process::Command, capture_stdout: bool| {+ cmd.stdin(std::process::Stdio::null());+ if capture_stdout {+ cmd.stdout(std::process::Stdio::piped());+ } else {+ cmd.stdout(std::process::Stdio::null());+ }+ cmd.stderr(std::process::Stdio::piped());+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ cmd.process_group(0);+ }+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x0000_0200);+ }+ cmd.spawn()+ };+ let is_android = matches!(kind, crate::tui::state::PlayerKind::AndroidIntent);+ let command = crate::tui::player::command(kind,&effective_link,effective_subtitle.as_deref(),@@ -397,32 +419,49 @@ impl App {"IINA opened without iina-cli: headers and subtitles unavailable.".to_string(),));}- let capture_stdout = matches!(kind, crate::tui::state::PlayerKind::AndroidIntent);- command.stdin(std::process::Stdio::null());- if capture_stdout {- command.stdout(std::process::Stdio::piped());- } else {- command.stdout(std::process::Stdio::null());- }- command.stderr(std::process::Stdio::piped());- #[cfg(unix)]- {- use std::os::unix::process::CommandExt;- command.process_group(0);- }- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- command.creation_flags(0x0000_0200);- }+ let spawn_result = if is_android {+ let candidates = crate::player::android_intent_commands(+ &effective_link,+ effective_subtitle.as_deref(),+ &headers,+ );+ let mut spawned = None;+ let mut last_err = None;+ for (opener, cmd) in candidates {+ match spawn_configured_command(cmd, true) {+ Ok(child) => {+ log::info!("spawned android opener: {opener:?}");+ spawned = Some(child);+ break;+ }+ Err(err) => {+ log::warn!("failed to spawn opener {opener:?}: {err}");+ last_err = Some(err);+ }+ }+ }+ match spawned {+ Some(child) => Ok(child),+ None => Err(last_err.unwrap_or_else(|| {+ std::io::Error::new(+ std::io::ErrorKind::NotFound,+ "No Android intent tools found",+ )+ })),+ }+ } else {+ spawn_configured_command(command, false)+ };- match command.spawn() {+ match spawn_result {Ok(mut child) => {let start_time = std::time::Instant::now();let stderr_stream = child.stderr.take();let stdout_stream = child.stdout.take();-+ let fallback_link = effective_link.clone();+ let fallback_sub = effective_subtitle.clone();+ let fallback_headers = headers.clone();tokio::task::spawn_blocking(move || {let mut error_output = String::new();let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();@@ -500,6 +539,56 @@ impl App {);}Ok(status) => {+ let is_termux_socket_err = is_android+ && (error_output.contains("am.sock")+ || error_output.contains("Could not connect to socket")+ || error_output.contains("termux-am"));++ if is_termux_socket_err {+ let fallback_candidates = crate::player::android_openers();+ let secondary = fallback_candidates.into_iter().find(|op| {+ matches!(+ op,+ crate::player::AndroidOpener::TermuxOpen(_)+ | crate::player::AndroidOpener::TermuxOpenUrl(_)+ )+ });+ if let Some(op) = secondary {+ log::warn!(+ "primary opener failed socket connection, retrying with fallback opener {op:?}"+ );+ let mut fallback_cmd =+ crate::player::android_intent_command_for_opener(+ &op,+ &fallback_link,+ fallback_sub.as_deref(),+ &fallback_headers,+ );+ fallback_cmd.stdin(std::process::Stdio::null());+ fallback_cmd.stdout(std::process::Stdio::piped());+ fallback_cmd.stderr(std::process::Stdio::piped());+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ fallback_cmd.process_group(0);+ }+ if let Ok(mut retry_child) = fallback_cmd.spawn() {+ if let Ok(retry_status) = retry_child.wait() {+ if retry_status.success() {+ log::info!(+ "fallback android opener {op:?} succeeded"+ );+ if let Some(path) = temporary_subtitle {+ let _ = std::fs::remove_file(path);+ }+ sender.send(Action::PlayerExited).ok();+ return;+ }+ }+ }+ }+ }+#[cfg(unix)]let signal = {use std::os::unix::process::ExitStatusExt;@@ -894,11 +983,10 @@ impl App {log::error!("player crashed (code {code_str}): {error_msg}");let is_termux = crate::updater::artifact::is_termux_environment();+ let error_lower = error_msg.to_ascii_lowercase();let is_missing_activity = is_termux- && (error_msg.contains("No Activity found")- || error_msg.contains("ActivityNotFoundException")- || error_msg.contains("no activity found"));-+ && (error_lower.contains("no activity found")+ || error_lower.contains("activitynotfoundexception"));let is_termux_tool_crash = is_termux&& (code == Some(126)|| error_msg.contains("Permission denied")@@ -913,31 +1001,27 @@ impl App {|| error_msg.contains("broadcast"))));let is_headless_mpv = is_termux- && (error_msg.contains("Failed to open display")- || error_msg.contains("video_out")- || error_msg.contains("vo/gpu")- || error_msg.contains("vo=gpu"));-+ && (error_lower.contains("failed to open display")+ || error_lower.contains("video_out")+ || error_lower.contains("vo/gpu")+ || error_lower.contains("vo=gpu"));let (title, message) = if is_missing_activity {+ ("No Player", "Install a video player.".to_string())+ } else if is_headless_mpv {(- "No Video Player",- "Install a video player on Android.".to_string(),+ "CLI mpv",+ "Switch to Android Player in /settings.".to_string(),)} else if is_termux_tool_crash {(- "Termux Setup Needed",- "Run: pkg install -y termux-am".to_string(),- )- } else if is_headless_mpv {- (- "CLI mpv Unsupported",- "Switch to Android Player in /settings.".to_string(),+ "Termux Setup",+ "Run 'pkg install termux-tools'.".to_string(),)} else {let formatted_msg = if let Some(c) = code {format!("Player exited (code {c}).")} else {- "Player process terminated.".to_string()+ "Player exited.".to_string()};("Playback Failed", formatted_msg)};@@ -1263,9 +1347,12 @@ mod tests {);}+ static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+#[tokio::test]async fn test_player_crashed_termux_actionable_notification() {let mut app = crate::tui::app::App::new();+ let _guard = ENV_LOCK.lock().await;unsafe {std::env::set_var("TERMUX_VERSION", "0.118.0");}@@ -1283,13 +1370,14 @@ mod tests {.notifications.back().expect("expected notification");- assert_eq!(last_notification.title, "Termux Setup Needed");- assert_eq!(last_notification.message, "Run: pkg install -y termux-am");+ assert_eq!(last_notification.title, "Termux Setup");+ assert_eq!(last_notification.message, "Run 'pkg install termux-tools'.");}#[tokio::test]async fn test_player_crashed_termux_missing_activity() {let mut app = crate::tui::app::App::new();+ let _guard = ENV_LOCK.lock().await;unsafe {std::env::set_var("TERMUX_VERSION", "0.118.0");}@@ -1306,16 +1394,14 @@ mod tests {.notifications.back().expect("expected notification");- assert_eq!(last_notification.title, "No Video Player");- assert_eq!(- last_notification.message,- "Install a video player on Android."- );+ assert_eq!(last_notification.title, "No Player");+ assert_eq!(last_notification.message, "Install a video player.");}#[tokio::test]async fn test_player_crashed_termux_headless_mpv() {let mut app = crate::tui::app::App::new();+ let _guard = ENV_LOCK.lock().await;unsafe {std::env::set_var("TERMUX_VERSION", "0.118.0");}@@ -1332,7 +1418,7 @@ mod tests {.notifications.back().expect("expected notification");- assert_eq!(last_notification.title, "CLI mpv Unsupported");+ assert_eq!(last_notification.title, "CLI mpv");assert_eq!(last_notification.message,"Switch to Android Player in /settings."@@ -1342,6 +1428,7 @@ mod tests {#[tokio::test]async fn test_player_crashed_termux_exit_code_1_generic() {let mut app = crate::tui::app::App::new();+ let _guard = ENV_LOCK.lock().await;unsafe {std::env::set_var("TERMUX_VERSION", "0.118.0");}@@ -1358,8 +1445,8 @@ mod tests {.notifications.back().expect("expected notification");- assert_eq!(last_notification.title, "Termux Setup Needed");- assert_eq!(last_notification.message, "Run: pkg install -y termux-am");+ assert_eq!(last_notification.title, "Termux Setup");+ assert_eq!(last_notification.message, "Run 'pkg install termux-tools'.");}#[tokio::test]diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rsindex 0ed20cf..a72684d 100644--- a/src/tui/app/requests.rs+++ b/src/tui/app/requests.rs@@ -81,7 +81,7 @@ impl App {let clean_title = if query.starts_with('/') {raw_title} else {- crate::providers::moviebox::clean_moviebox_title(&raw_title)+ crate::providers::moviebox::clean_moviebox_title(&raw_title).to_string()};if query.starts_with('/') {@@ -332,7 +332,7 @@ impl App {self.state.search_results.iter_mut().find(|r| r.id == id){if existing.title.is_empty() {- existing.title = clean_title;+ existing.title = clean_title.to_string();existing.stype = stype;existing.release_year = release_year;existing.cover_url = cover_url;@@ -365,7 +365,7 @@ impl App {if !id.is_empty() {self.state.search_results.push(SearchResult {id,- title: clean_title,+ title: clean_title.to_string(),stype,release_year,cover_url,diff --git a/src/tui/app/search.rs b/src/tui/app/search.rsindex 394af1a..b414e3f 100644--- a/src/tui/app/search.rs+++ b/src/tui/app/search.rs@@ -538,7 +538,7 @@ impl App {stored_metrics.recent_rating.or(metrics.recent_rating);stored_metrics.popularity = stored_metrics.popularity.or(metrics.popularity);if existing.title.is_empty() {- existing.title = clean_title;+ existing.title = clean_title.to_string();existing.stype = stype;existing.release_year = release_year;existing.cover_url = cover_url;@@ -572,7 +572,7 @@ impl App {self.state.browse_metrics.insert(id.clone(), metrics);self.state.search_results.push(SearchResult {id,- title: clean_title,+ title: clean_title.to_string(),stype,release_year,cover_url,diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rsindex e055e53..dba65b7 100644--- a/src/tui/screens/details.rs+++ b/src/tui/screens/details.rs@@ -469,11 +469,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)} else {theme.title.add_modifier(Modifier::BOLD)};- let title_w = crate::tui::text::width(&title);+ let title_w = crate::tui::text::width(title);if title_w <= text_width {- rendered_lines.push(Line::from(vec![Span::styled(title.clone(), title_style)]));+ rendered_lines.push(Line::from(vec![Span::styled(title, title_style)]));} else {- let wrapped_title = crate::tui::text::wrap_text(&title, text_width);+ 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, title_style)]));}@@ -983,7 +983,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)} else if let Some(hist) =state.history- .get_item(provider, subject_id, se_num, ep, Some(&title))+ .get_item(provider, subject_id, se_num, ep, Some(title)){if hist.completed {theme.text_dim@@ -1000,7 +1000,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)let sym = if let Some(hist) =state.history- .get_item(provider, subject_id, se_num, ep, Some(&title))+ .get_item(provider, subject_id, se_num, ep, Some(title)){if hist.completed {check_sym@@ -1016,7 +1016,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)};let progress_info = state.history- .get_item(provider, subject_id, se_num, ep, Some(&title))+ .get_item(provider, subject_id, se_num, ep, Some(title)).filter(|h| !h.completed && h.is_in_progress()).map(|h| match (h.progress_percentage(), h.formatted_remaining()) {diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex 6bfcb3e..da435b5 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -1300,13 +1300,13 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)basic_terminal,state.landing_deck_visible(),);- let vertical_chunks = rows.rects.clone();+ let vertical_chunks = &rows.rects;- let logo_text = if basic_terminal || tier.is_compact() {+ let logo_text: &'static str = if basic_terminal || tier.is_compact() {if state.is_tv_mode {- "█▀▄▀█ █▀█ █ █ █ █▀▀ █▀▄ █▀█ ▀▄▀\n█ ▀ █ █▄█ ▀▄▀ █ ██▄ █▄▀ █▄█ █ █TV".to_string()+ "█▀▄▀█ █▀█ █ █ █ █▀▀ █▀▄ █▀█ ▀▄▀\n█ ▀ █ █▄█ ▀▄▀ █ ██▄ █▄▀ █▄█ █ █TV"} else {- "█▀▄▀█ █▀█ █ █ █ █▀▀ █▀▄ █▀█ ▀▄▀\n█ ▀ █ █▄█ ▀▄▀ █ ██▄ █▄▀ █▄█ █ █".to_string()+ "█▀▄▀█ █▀█ █ █ █ █▀▀ █▀▄ █▀█ ▀▄▀\n█ ▀ █ █▄█ ▀▄▀ █ ██▄ █▄▀ █▄█ █ █"}} else if state.is_tv_mode {r"███╗ ███╗ ██████╗ ██╗ ██╗ ██╗ ███████╗ ██████╗ ██████╗ ██╗ ██╗@@ -1315,7 +1315,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)██║╚██╔╝██║ ██║ ██║ ╚██╗ ██╔╝ ██║ ██╔══╝ ██╔══██╗ ██║ ██║ ██╔██╗ TV██║ ╚═╝ ██║ ╚██████╔╝ ╚████╔╝ ██║ ███████╗ ██████╔╝ ╚██████╔╝ ██╔╝ ██╗╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"- .to_string()} else {r"███╗ ███╗ ██████╗ ██╗ ██╗ ██╗ ███████╗ ██████╗ ██████╗ ██╗ ██╗████╗ ████║ ██╔═══██╗ ██║ ██║ ██║ ██╔════╝ ██╔══██╗ ██╔═══██╗ ╚██╗██╔╝@@ -1323,7 +1322,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)██║╚██╔╝██║ ██║ ██║ ╚██╗ ██╔╝ ██║ ██╔══╝ ██╔══██╗ ██║ ██║ ██╔██╗██║ ╚═╝ ██║ ╚██████╔╝ ╚████╔╝ ██║ ███████╗ ██████╔╝ ╚██████╔╝ ██╔╝ ██╗╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"- .to_string()};let logo_width: u16 = rows.logo_width;@@ -1440,7 +1438,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)crate::tui::clear_area(frame, results_chunk, theme);let selected_idx = state.search_list_state.selected();- let metrics = state.result_metrics(results_area.height, results_area.width);+ let metrics = if has_scrollbar {+ state.result_metrics(results_area.height, results_area.width)+ } else {+ initial_metrics+ };let target_width = if state.image_supported {state.image_pickerdiff --git a/src/tui/theme.rs b/src/tui/theme.rsindex 200f2fa..7645c13 100644--- a/src/tui/theme.rs+++ b/src/tui/theme.rs@@ -125,7 +125,14 @@ impl ColorSupport {if std::env::var("NO_COLOR").is_ok_and(|v| !v.is_empty()) {return ColorSupport::NoColor;}- if std::env::var("WT_SESSION").is_ok() {+ if std::env::var("WT_SESSION").is_ok()+ || std::env::var("WEZTERM_EXECUTABLE").is_ok()+ || std::env::var("ALACRITTY_WINDOW_ID").is_ok()+ || std::env::var("TILIX_ID").is_ok()+ || std::env::var("VTE_VERSION")+ .ok()+ .is_some_and(|v| is_vte_version_truecolor(&v))+ {return ColorSupport::Truecolor;}let colorterm = std::env::var("COLORTERM").unwrap_or_default();@@ -145,6 +152,10 @@ impl ColorSupport {}}+pub(crate) fn is_vte_version_truecolor(vte_version: &str) -> bool {+ vte_version.parse::<u32>().ok().is_some_and(|v| v >= 3600)+}+pub(crate) fn classify_terminal(colorterm: &str, term: &str, term_program: &str) -> ColorSupport {let colorterm = colorterm.to_lowercase();let term = term.to_lowercase();@@ -165,14 +176,7 @@ pub(crate) fn classify_terminal(colorterm: &str, term: &str, term_program: &str)|| term_program == "vscode"|| term_program == "ghostty"|| term_program == "konsole"- || term_program == "xfce4-terminal"- || std::env::var("VTE_VERSION")- .ok()- .and_then(|v| v.parse::<u32>().ok())- .is_some_and(|v| v >= 3600)- || std::env::var("WEZTERM_EXECUTABLE").is_ok()- || std::env::var("ALACRITTY_WINDOW_ID").is_ok()- || std::env::var("TILIX_ID").is_ok();+ || term_program == "xfce4-terminal";let basic =term == "dumb" || term == "linux" || term.contains("fbterm") || term.starts_with("vt");let apple_term = term.contains("apple") || term_program == "apple_terminal";@@ -1092,17 +1096,10 @@ mod tests {#[test]fn vte_version_threshold_respects_truecolor_boundary() {- unsafe {- std::env::set_var("VTE_VERSION", "3599");- }- assert_ne!(classify_terminal("", "xterm", ""), ColorSupport::Truecolor);- unsafe {- std::env::set_var("VTE_VERSION", "3600");- }- assert_eq!(classify_terminal("", "xterm", ""), ColorSupport::Truecolor);- unsafe {- std::env::remove_var("VTE_VERSION");- }+ assert!(!is_vte_version_truecolor("3599"));+ assert!(is_vte_version_truecolor("3600"));+ assert!(is_vte_version_truecolor("4000"));+ assert!(!is_vte_version_truecolor("invalid"));}#[test]diff --git a/tests/performance_audit.rs b/tests/performance_audit.rsindex 20ec7a8..1f929f6 100644--- a/tests/performance_audit.rs+++ b/tests/performance_audit.rs@@ -132,6 +132,21 @@ fn test_benchmark_performance_improvements_matrix() {assert!(opt_md5_duration <= baseline_md5_duration);}+ let mut clean_title_duration = std::time::Duration::MAX;+ for _ in 0..3 {+ let t = Instant::now();+ for i in 0..ITERATIONS {+ let title = sample_titles[i % sample_titles.len()];+ let _ = moviebox_tui::providers::moviebox::clean_moviebox_title(title);+ }+ clean_title_duration = clean_title_duration.min(t.elapsed());+ }+ println!(+ "BENCHMARK: clean_moviebox_title ({} ops)\n Duration: {:?} ({:.2} ns/op)",+ ITERATIONS,+ clean_title_duration,+ clean_title_duration.as_nanos() as f64 / ITERATIONS as f64+ );let mut playlist_data = String::from("#EXTM3U\n");for i in 0..500 {playlist_data.push_str(&format!(