Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(cache): harden cross-platform cache clearing and centralize tui widgets
Samir Hossainsf20c20bfe36e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e431541..b1d0cd3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,12 +24,24 @@- **Empirical Performance Standards & Benchmark Testing Guidelines**:- Added strict performance verification standards requiring empirical before-and-after measurements (runtime latency, allocations, frame render latency, I/O syscalls, binary footprint) across hot paths.- Documented standardized performance benchmark reporting format in `docs/testing.md` for reproducible optimization audits.+- **Centralized Poster Placeholder & UI Animation Widgets**:+ - Extracted reusable `render_poster_placeholder` widget to `src/tui/widgets/poster.rs`, standardizing placeholder containers, loading dots, and geometry clamping across Home and Details screens.+ - Centralized `loading_spinner` in `src/tui/widgets`, providing uniform ASCII fallback (`..`, `...`) on basic terminals and animated Braille frames on modern terminals.+ - Added zero-allocation cursor helpers (`cursor_prefix_str`, `cursor_column_offset`, `cursor_split_parts`) to `TextInputBuffer`, replacing dynamic vector and string allocations with zero-copy slices during typing and cursor blinking.+ - Added `step_list_selection` to `src/tui/state.rs`, centralizing bounds-safe list stepping for PageUp and PageDown navigation across browse, theme, and favorites lists.+ - Added `clear_poster_cache` and `clear_poster_protocols` to `AppState`, guaranteeing consistent flushing of in-flight requests, LRU image handles, and terminal protocols across provider switches and search resets.### 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).### Fixed+- **Resilient Cross-Platform Cache Clearing & In-Flight Task Isolation**:+ - Hardened `clear_all_cache` with recursive directory contents deletion, leaving the root directory node intact to prevent `ERROR_ACCESS_DENIED` and `ERROR_SHARING_VIOLATION` failures when Windows processes or shells hold folder handles.+ - Added Windows read-only attribute clearing before unlinking locked files.+ - Included external Android subtitle cache directory (`~/storage/downloads/moviebox_subs`) and temporary system subtitle caches in the cache purge sequence.+ - Connected `Action::ClearCache` directly to `self.request_tasks.cancel_all()` and added cancellation guards in `spawn_search_posters`, preventing in-flight background requests from writing stale responses or posters immediately after cache clearance.+ - Propagated concrete filesystem `Result<(), String>` to `Action::CacheCleared`, replacing hardcoded success notifications with real error reporting.- **Unified Search Result Selection Background**:- Unified search result card selection highlight across the entire item slot (`item_area`), eliminating fragmented background rendering between cursor indicators, posters, and text columns.- Removed redundant poster sub-area buffer clearing before image rendering, preventing selection background clipping and black gutter artifacts on the right edge of posters.@@ -41,6 +53,8 @@- Pre-registered media playback on launch (`record_start`), ensuring immediate watch history persistence for Android intent dispatchers (`termux-open`, `am start`) and app fallbacks.- Added self-healing recovery in `reconcile_from_dir`: pre-seeded pending state files carry metadata (`title`, `cover_url`, `stype`, `release_year`), restoring new items into watch history even after sudden terminal exits or reboots.- Implemented smart series episode advancement: completing an episode automatically cues the next episode (`episode + 1` or next season) on resume (`Space`/`P`) and in the Details view.+- **Details View Empty Stream Source Label Geometry**:+ - Replaced verbose empty stream message with a compact string (`No stream sources found on {provider} (Ctrl+P to switch provider, r to retry)`), preventing awkward multi-line text wrapping on standard 80-column terminals.- **Standardized 'No Art' Poster Containers Across Terminals**:- Replaced robot eyes and broken infinite loading spinners with clean, static, centered `No Art` bordered blocks across search results and details screens on terminals without graphics support.- Preserved full-fidelity native GPU graphics rendering on supported terminals while standardizing card geometry and poster container boundaries across all platforms.diff --git a/docs/architecture.md b/docs/architecture.mdindex 8baa2b2..3a690f1 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -60,7 +60,8 @@ src/screens/ render-only modules (home, details, help)terminal.rs terminal capability probestheme.rs color themes- text.rs grapheme-safe text helpers+ widgets/ reusable widgets (badge, input, modal, poster, scrollbar, settings)+ text.rs grapheme-safe text helpers and zero-allocation cursor slicing```## The event loopdiff --git a/docs/cache.md b/docs/cache.mdindex a4427fa..f8bdb08 100644--- a/docs/cache.md+++ b/docs/cache.md@@ -31,7 +31,7 @@ The cache directory is `dirs::cache_dir()/moviebox-tui` (macOS- **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. `/settings` $\to$ Maintenance $\to$ Clear Cache purges the entire cache tree and resets in-memory LRUs.+- **Purge**: Background cleanup runs at startup to delete entries older than 7 days. `/settings` $\to$ Maintenance $\to$ Clear Disk Cache recursively empties all cached provider responses, images, TV playlists, temporary subtitles across Android/Windows/Unix, resets in-memory LRU caches, and cancels in-flight background request tasks.## In-memory caches (AppState)diff --git a/docs/modules.md b/docs/modules.mdindex a25744f..37f3b4e 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -103,6 +103,7 @@ src/input.rs Single-line text input field rendering with grapheme cursor and truncation.modal.rs Modal dialog frame builder (ModalFrame) and centered footer key action bars.scrollbar.rs Viewport-accurate vertical scrollbars.+ poster.rs Standardized poster placeholder container with in-flight loading animation.settings.rs Interactive 4-tab Settings Hub modal widget.tui/app/ The application object (App) and all behavior.diff --git a/src/cache.rs b/src/cache.rsindex 32dfdcf..aa5763e 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -490,17 +490,147 @@ pub fn set_captions_cache_typed(subject_id: &str, resource_id: &str, captions: &set_typed_cache(&path, CACHE_EXPIRY_SECS, captions);}-pub fn clear_all_cache() {+fn resilient_remove_file(path: &Path) -> std::io::Result<()> {+ match fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(err) => {+ #[cfg(windows)]+ if let Ok(metadata) = fs::metadata(path) {+ let mut permissions = metadata.permissions();+ if permissions.readonly() {+ permissions.set_readonly(false);+ if fs::set_permissions(path, permissions).is_ok() {+ return fs::remove_file(path);+ }+ }+ }+ Err(err)+ }+ }+}++pub fn clear_directory_contents(dir: &Path) -> Result<(), String> {+ if !dir.exists() {+ return Ok(());+ }++ let mut errors = Vec::new();+ let entries = match fs::read_dir(dir) {+ Ok(entries) => entries,+ Err(err) => {+ if err.kind() == std::io::ErrorKind::NotFound {+ return Ok(());+ }+ return Err(format!("failed to read directory {}: {err}", dir.display()));+ }+ };++ for entry in entries.flatten() {+ let child_path = entry.path();+ match entry.file_type() {+ Ok(ft) if ft.is_dir() => {+ if let Err(err) = clear_directory_contents(&child_path) {+ errors.push(err);+ }+ if let Err(err) = fs::remove_dir(&child_path) {+ if err.kind() != std::io::ErrorKind::NotFound {+ errors.push(format!(+ "failed to remove directory {}: {err}",+ child_path.display()+ ));+ }+ }+ }+ _ => {+ if let Err(err) = resilient_remove_file(&child_path) {+ if err.kind() != std::io::ErrorKind::NotFound {+ errors.push(format!(+ "failed to remove file {}: {err}",+ child_path.display()+ ));+ }+ }+ }+ }+ }++ if errors.is_empty() {+ Ok(())+ } else {+ Err(errors.join("; "))+ }+}++fn purge_subtitle_cache_files(dir: &Path, errors: &mut Vec<String>) {+ if !dir.exists() {+ return;+ }+ let entries = match fs::read_dir(dir) {+ Ok(entries) => entries,+ Err(err) => {+ if err.kind() != std::io::ErrorKind::NotFound {+ errors.push(format!(+ "failed to read subtitle directory {}: {err}",+ dir.display()+ ));+ }+ return;+ }+ };++ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_file() {+ if let Some(ext) = path.extension().and_then(|s| s.to_str()) {+ let lower = ext.to_ascii_lowercase();+ if matches!(lower.as_str(), "srt" | "vtt" | "sub" | "ass" | "tmp") {+ if let Err(err) = resilient_remove_file(&path) {+ if err.kind() != std::io::ErrorKind::NotFound {+ errors.push(format!(+ "failed to remove subtitle file {}: {err}",+ path.display()+ ));+ }+ }+ }+ }+ }+ }+}++pub fn clear_all_cache() -> Result<(), String> {+ let mut errors = Vec::new();let path = crate::config::cache_dir();if path.exists() {- let _ = fs::remove_dir_all(&path);+ if let Err(err) = clear_directory_contents(&path) {+ errors.push(err);+ }}if let Some(data_dir) = crate::config::data_dir() {let legacy = data_dir.join("iptv_cache");if legacy.exists() {- let _ = fs::remove_dir_all(&legacy);+ if let Err(err) = clear_directory_contents(&legacy) {+ errors.push(err);+ }+ let _ = fs::remove_dir(&legacy);}}+ if let Some(home) = dirs::home_dir() {+ let storage = home.join("storage/downloads/moviebox_subs");+ if storage.exists() {+ purge_subtitle_cache_files(&storage, &mut errors);+ }+ }+ let temp_subs = std::env::temp_dir().join("moviebox-tui").join("subs");+ if temp_subs.exists() {+ purge_subtitle_cache_files(&temp_subs, &mut errors);+ }++ if errors.is_empty() {+ Ok(())+ } else {+ Err(errors.join("; "))+ }}pub fn clean_old_cache_background() {@@ -682,4 +812,41 @@ mod tests {assert_eq!(md5_hex(""), "d41d8cd98f00b204e9800998ecf8427e");assert_ne!(md5_hex("query1"), md5_hex("query2"));}+ #[test]+ fn test_clear_directory_contents_removes_nested_entries_and_preserves_root() {+ let dir = unique_dir("clear_nested");+ let sub1 = dir.join("moviebox").join("details");+ let sub2 = dir.join("moviebox").join("images");+ let sub3 = dir.join("tv_playlists");+ fs::create_dir_all(&sub1).expect("create sub1");+ fs::create_dir_all(&sub2).expect("create sub2");+ fs::create_dir_all(&sub3).expect("create sub3");++ fs::write(sub1.join("detail_1.cache"), b"details").expect("write detail");+ fs::write(sub2.join("img_1.bin"), b"image").expect("write img");+ fs::write(sub3.join("channels.m3u"), b"m3u").expect("write m3u");+ fs::write(dir.join("root_file.tmp"), b"root").expect("write root file");++ let result = clear_directory_contents(&dir);+ assert!(result.is_ok());+ assert!(dir.exists());+ let remaining = fs::read_dir(&dir).expect("read dir").count();+ assert_eq!(remaining, 0);+ let _ = fs::remove_dir_all(&dir);+ }++ #[test]+ fn test_clear_directory_contents_handles_nonexistent_directory() {+ let dir = unique_dir("nonexistent");+ let missing = dir.join("missing_sub");+ let result = clear_directory_contents(&missing);+ assert!(result.is_ok());+ let _ = fs::remove_dir_all(&dir);+ }++ #[test]+ fn test_clear_all_cache_returns_ok() {+ let result = clear_all_cache();+ assert!(result.is_ok());+ }}diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rsindex 37de752..383edb7 100644--- a/src/tui/app/keyboard.rs+++ b/src/tui/app/keyboard.rs@@ -170,20 +170,18 @@ impl App {}}KeyCode::PageUp => {- if total_count > 0 {- let cur = self.state.browse_list_state.selected().unwrap_or(0);- self.state- .browse_list_state- .select(Some(cur.saturating_sub(5)));- }+ crate::tui::state::step_list_selection(+ &mut self.state.browse_list_state,+ total_count,+ -5,+ );}KeyCode::PageDown => {- if total_count > 0 {- let cur = self.state.browse_list_state.selected().unwrap_or(0);- self.state- .browse_list_state- .select(Some((cur + 5).min(total_count - 1)));- }+ crate::tui::state::step_list_selection(+ &mut self.state.browse_list_state,+ total_count,+ 5,+ );}KeyCode::Enter => {let index = self.state.browse_list_state.selected().unwrap_or(0);@@ -282,10 +280,12 @@ impl App {}KeyCode::PageUp => {let total = crate::tui::theme::AVAILABLE_THEMES.len();- if total > 0 {- let cur = self.state.theme_list_state.selected().unwrap_or(0);- let next = cur.saturating_sub(5);- self.state.theme_list_state.select(Some(next));+ crate::tui::state::step_list_selection(+ &mut self.state.theme_list_state,+ total,+ -5,+ );+ if let Some(next) = self.state.theme_list_state.selected() {let selected_theme = crate::tui::theme::AVAILABLE_THEMES[next].to_string();self.action_sender.send(Action::SelectTheme(selected_theme))@@ -294,10 +294,12 @@ impl App {}KeyCode::PageDown => {let total = crate::tui::theme::AVAILABLE_THEMES.len();- if total > 0 {- let cur = self.state.theme_list_state.selected().unwrap_or(0);- let next = (cur + 5).min(total - 1);- self.state.theme_list_state.select(Some(next));+ crate::tui::state::step_list_selection(+ &mut self.state.theme_list_state,+ total,+ 5,+ );+ if let Some(next) = self.state.theme_list_state.selected() {let selected_theme = crate::tui::theme::AVAILABLE_THEMES[next].to_string();self.action_sender.send(Action::SelectTheme(selected_theme))@@ -829,14 +831,12 @@ impl App {}KeyCode::PageDown => {if self.state.favorites_focus {- let cur =- self.state.favorites_landing_state.selected().unwrap_or(0);let total = self.state.landing_deck_items_count();- if total > 0 {- self.state- .favorites_landing_state- .select(Some((cur + 5).min(total - 1)));- }+ crate::tui::state::step_list_selection(+ &mut self.state.favorites_landing_state,+ total,+ 5,+ );} else if !self.state.search_results.is_empty() {let step = self.state@@ -859,11 +859,12 @@ impl App {}KeyCode::PageUp => {if self.state.favorites_focus {- let cur =- self.state.favorites_landing_state.selected().unwrap_or(0);- self.state- .favorites_landing_state- .select(Some(cur.saturating_sub(5)));+ let total = self.state.landing_deck_items_count();+ crate::tui::state::step_list_selection(+ &mut self.state.favorites_landing_state,+ total,+ -5,+ );} else if !self.state.search_results.is_empty() {let step = self.statediff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rsindex ea4fe74..5c250e9 100644--- a/src/tui/app/navigation.rs+++ b/src/tui/app/navigation.rs@@ -51,14 +51,9 @@ impl App {self.state.download_queue.clear();self.state.download_queue_total = 0;self.state.is_waiting_for_download_stream = false;- self.state.search_posters.clear();- self.state.failed_posters.clear();- self.state.search_poster_protocols.clear();- self.state.in_flight_posters.clear();+ self.state.clear_poster_cache();self.state.image_cache.clear();self.state.preview_cache.clear();- self.state.poster_image = None;- self.state.poster_protocol = None;self.state.search_list_state.select(None);self.state.resource_list_state.select(None);self.state.dirty = true;@@ -105,8 +100,7 @@ impl App {}pub(super) fn prepare_image_soft_refresh(&mut self) {- self.state.poster_protocol = None;- self.state.search_poster_protocols.clear();+ self.state.clear_poster_protocols();self.state.dirty = true;}diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rsindex 4376969..ad1c806 100644--- a/src/tui/app/requests.rs+++ b/src/tui/app/requests.rs@@ -474,12 +474,7 @@ impl App {self.state.search_results.clear();self.state.search_list_state.select(None);self.state.search_preview = None;- self.state.poster_image = None;- self.state.poster_protocol = None;- self.state.search_posters.clear();- self.state.failed_posters.clear();- self.state.search_poster_protocols.clear();- self.state.in_flight_posters.clear();+ self.state.clear_poster_cache();}self.state.search_error = Some(err.clone());self.state@@ -575,12 +570,7 @@ impl App {self.state.search_results.clear();self.state.search_list_state.select(None);self.state.search_preview = None;- self.state.poster_image = None;- self.state.poster_protocol = None;- self.state.search_posters.clear();- self.state.failed_posters.clear();- self.state.search_poster_protocols.clear();- self.state.in_flight_posters.clear();+ self.state.clear_poster_cache();self.state.set_status_default(format!("Discover failed: {}", err));}diff --git a/src/tui/app/run.rs b/src/tui/app/run.rsindex 15f51d3..f99d35c 100644--- a/src/tui/app/run.rs+++ b/src/tui/app/run.rs@@ -98,8 +98,7 @@ impl App {log::debug!("terminal clear warning: {err}");let _ = terminal.backend_mut().clear();}- self.state.poster_protocol = None;- self.state.search_poster_protocols.clear();+ self.state.clear_poster_protocols();self.state.clear_terminal_before_draw = false;self.state.dirty = true;}@@ -1021,10 +1020,8 @@ impl App {).render(frame, popup_area, area);- let spinner = crate::tui::screens::details::stream_loading_spinner(- self.state.tick_count,- self.state.basic_terminal,- );+ let spinner =+ crate::tui::widgets::loading_spinner(self.state.tick_count, self.state.basic_terminal);let target_version = self.statediff --git a/src/tui/app/search.rs b/src/tui/app/search.rsindex 3b60d12..4d38455 100644--- a/src/tui/app/search.rs+++ b/src/tui/app/search.rs@@ -651,6 +651,7 @@ impl App {let sender = self.action_sender.clone();let service = self.service.clone();let semaphore = self.state.poster_fetch_semaphore.clone();+ let cancel_token = self.state.fetch_cancel.clone();tokio::spawn(async move {let sem = semaphore;@@ -658,9 +659,13 @@ impl App {let permit = sem.clone().acquire_owned().await.ok();let tx = sender.clone();let service = service.clone();+ let cancel = cancel_token.clone();tokio::spawn(async move {let _permit = permit;+ if cancel.load(std::sync::atomic::Ordering::Relaxed) {+ return;+ }let id_clone = id.clone();if let Ok(Some(bytes)) = tokio::task::spawn_blocking({let id_c = id_clone.clone();@@ -685,6 +690,9 @@ impl App {if let Some(url) = resolved_url {if !url.is_empty() {if let Some(bytes) = service.fetch_poster_bytes(&url).await {+ if cancel.load(std::sync::atomic::Ordering::Relaxed) {+ return;+ }let bytes_clone = bytes.clone();let id_c = id.clone();let _ = tokio::task::spawn_blocking(move || {@@ -696,6 +704,10 @@ impl App {}).await;+ if cancel.load(std::sync::atomic::Ordering::Relaxed) {+ return;+ }+if let Some(img) = network::decode_poster(bytes).await {tx.send(Action::SearchPosterLoaded(id, Some(img))).ok();return;diff --git a/src/tui/app/system.rs b/src/tui/app/system.rsindex 81ce1bf..2663c2e 100644--- a/src/tui/app/system.rs+++ b/src/tui/app/system.rs@@ -33,8 +33,7 @@ impl App {if time.elapsed() >= std::time::Duration::from_millis(300) {self.state.last_resize_time = None;self.state.clear_terminal_before_draw = true;- self.state.poster_protocol = None;- self.state.search_poster_protocols.clear();+ self.state.clear_poster_protocols();}}if needs_redraw {@@ -113,8 +112,7 @@ impl App {Action::Resize(w, h) => {self.state.last_resize_time = Some((std::time::Instant::now(), w, h));- self.state.poster_protocol = None;- self.state.search_poster_protocols.clear();+ self.state.clear_poster_protocols();self.state.dirty = true;}@@ -211,15 +209,13 @@ impl App {},Action::ClearCache => {+ self.request_tasks.cancel_all();let sender = self.action_sender.clone();tokio::spawn(async move {- let result = tokio::task::spawn_blocking(|| {- crate::cache::clear_all_cache();- Ok::<(), String>(())- })- .await- .map_err(|error| format!("cache clear task failed: {error}"))- .and_then(|result| result);+ let result = tokio::task::spawn_blocking(crate::cache::clear_all_cache)+ .await+ .map_err(|error| format!("cache clear task failed: {error}"))+ .and_then(|result| result);sender.send(Action::CacheCleared(result)).ok();});self.statediff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rsindex 0d6d693..05a91f8 100644--- a/src/tui/screens/details.rs+++ b/src/tui/screens/details.rs@@ -1,5 +1,8 @@use crate::models::MediaDetails;-pub(crate) use crate::tui::widgets::{extract_media_tags, resolution_badge_spans};+pub(crate) use crate::tui::widgets::{+ extract_media_tags, loading_spinner as stream_loading_spinner, render_poster_placeholder,+ resolution_badge_spans,+};use crate::tui::{state::AppState, theme::Theme};use ratatui::{Frame,@@ -421,45 +424,16 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)}}}- } else if state.image_supported && (state.is_loading || state.preview_loading) {- let loading_block = Block::default()- .borders(Borders::ALL)- .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 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}")- };- let placeholder = Paragraph::new(placeholder_text)- .alignment(Alignment::Center)- .style(theme.overlay0)- .block(loading_block);- frame.render_widget(placeholder, poster_area);} else {- let art_block = Block::default()- .borders(Borders::ALL)- .border_type(crate::tui::overlay::border_type(state.basic_terminal))- .border_style(theme.surface0);- let label = if state.basic_terminal {- "[No Art]"- } else {- "No Art"- };- let pad_top = poster_area.height.saturating_sub(3) / 2;- let content = format!("{}{label}", "\n".repeat(pad_top as usize));- let placeholder = Paragraph::new(content)- .alignment(Alignment::Center)- .style(theme.overlay0)- .block(art_block);- frame.render_widget(placeholder, poster_area);+ let is_in_flight = state.image_supported && (state.is_loading || state.preview_loading);+ render_poster_placeholder(+ frame,+ poster_area,+ theme,+ state.basic_terminal,+ is_in_flight,+ state.tick_count,+ );}chunks[2]@@ -1274,7 +1248,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)}} 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."+ "No stream sources found on {provider_label} (Ctrl+P to switch provider, r to retry)")} else {let spinner = stream_loading_spinner(state.tick_count, state.basic_terminal);@@ -1540,21 +1514,6 @@ fn metadata_style(theme: &Theme) -> Style {theme.subtext1}-const BRAILLE_SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];--pub(crate) fn stream_loading_spinner(tick_count: u64, basic_terminal: bool) -> &'static str {- if basic_terminal {- match (tick_count / 4) % 4 {- 0 => "..",- 1 => "...",- 2 => "....",- _ => "..",- }- } else {- BRAILLE_SPINNER[(tick_count as usize) % BRAILLE_SPINNER.len()]- }-}-fn with_selection_surface(style: Style, basic_terminal: bool, theme: &Theme) -> Style {if basic_terminal {stylediff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex 5c59bba..c31702b 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -1,3 +1,4 @@+use crate::tui::widgets::render_poster_placeholder;use crate::tui::{state::{AppState, InputMode},theme::Theme,@@ -49,68 +50,6 @@ pub(crate) fn slash_command_description(cmd: &str, state: &AppState) -> Option<&crate::tui::commands::SlashCommand::description_for(cmd, state)}-pub(crate) fn render_poster_placeholder(- frame: &mut Frame,- area: Rect,- theme: &Theme,- basic_terminal: bool,- is_in_flight: bool,- tick: u64,-) {- if area.width < 2 || area.height < 2 {- return;- }- let border_type = crate::tui::overlay::border_type(basic_terminal);- let border_style = if is_in_flight {- theme.lavender- } else {- theme.surface1- };- let block = Block::default()- .borders(Borders::ALL)- .border_type(border_type)- .border_style(border_style);- let inner = block.inner(area);- frame.render_widget(block, area);-- if inner.height == 0 || inner.width == 0 {- return;- }-- let pad_top = inner.height.saturating_sub(1) / 2;- let text_area = Rect {- x: inner.x,- y: inner.y + pad_top,- width: inner.width,- height: 1.min(inner.height),- };-- if is_in_flight {- let dots = match (tick / 4) % 4 {- 0 => "·",- 1 => "··",- 2 => "···",- _ => "····",- };- let p = Paragraph::new(dots)- .style(theme.lavender)- .alignment(Alignment::Center);- frame.render_widget(p, text_area);- } else {- let label = if inner.width >= 8 {- if basic_terminal { "[No Art]" } else { "No Art" }- } else if inner.width >= 6 {- "No Art"- } else {- "·"- };- let p = Paragraph::new(label)- .style(theme.overlay0)- .alignment(Alignment::Center);- frame.render_widget(p, text_area);- }-}-#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum HomeLayoutTier {Compact,@@ -255,10 +194,8 @@ fn render_search_state(};lines.push(Line::from(vec![Span::styled(text, theme.lavender)]));} else {- const SPINNER_FRAMES: [&str; 10] =- ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];let spinner =- SPINNER_FRAMES[(state.tick_count as usize / 2) % SPINNER_FRAMES.len()];+ crate::tui::widgets::loading_spinner(state.tick_count, state.basic_terminal);let text = if let Some(preset) = state.active_browse_preset {format!("Loading {}", preset.label())} else if let Some(catalog) = &state.active_addon_catalog {@@ -988,20 +925,11 @@ fn search_content(format!("{prefix}{content}")}} else if editing && !real_cursor {- let segments = state.search_query.graphemes();- let cursor = state.search_query.cursor();+ let (before, cursor_grapheme, after) = state.search_query.cursor_split_parts();let cursor_char = if show_cursor {if state.basic_terminal { "█" } else { "▎" }- } else if cursor < segments.len() {- segments[cursor]- } else {- " "- };- let before: String = segments.iter().take(cursor).copied().collect();- let after: String = if cursor < segments.len() {- segments.iter().skip(cursor + 1).copied().collect()} else {- String::new()+ cursor_grapheme};let full = format!("{before}{cursor_char}{after}");let truncated = crate::tui::text::truncate_width(&full, available);@@ -1199,20 +1127,11 @@ fn render_search_bar(])}} else if editing && !real_cursor && !modal_active {- let segments = state.search_query.graphemes();- let cursor = state.search_query.cursor();+ let (before, cursor_grapheme, after) = state.search_query.cursor_split_parts();let cursor_char = if show_cursor {if state.basic_terminal { "█" } else { "▎" }- } else if cursor < segments.len() {- segments[cursor]} else {- " "- };- let before: String = segments.iter().take(cursor).copied().collect();- let after: String = if cursor < segments.len() {- segments.iter().skip(cursor + 1).copied().collect()- } else {- String::new()+ cursor_grapheme};Line::from(vec![Span::styled(prefix, prefix_style),@@ -1243,11 +1162,9 @@ fn render_search_bar(let cx = if is_query_empty {search_split[0].x + prefix_width} else {- let segments = state.search_query.graphemes();- let cursor = state.search_query.cursor();- let before_cursor: String = segments.into_iter().take(cursor).collect();- let before_cursor_width = crate::tui::text::width(&before_cursor) as u16;- (search_split[0].x + prefix_width + before_cursor_width)+ (search_split[0].x+ + prefix_width+ + state.search_query.cursor_column_offset() as u16).min(search_split[0].right().saturating_sub(1))};frame.set_cursor_position((cx, search_split[0].y));@@ -1344,20 +1261,11 @@ fn render_search_bar(])}} else if editing && !real_cursor {- let segments = state.search_query.graphemes();- let cursor = state.search_query.cursor();+ let (before, cursor_grapheme, after) = state.search_query.cursor_split_parts();let cursor_char = if show_cursor {if state.basic_terminal { "█" } else { "▎" }- } else if cursor < segments.len() {- segments[cursor]- } else {- " "- };- let before: String = segments.iter().take(cursor).copied().collect();- let after: String = if cursor < segments.len() {- segments.iter().skip(cursor + 1).copied().collect()} else {- String::new()+ cursor_grapheme};Line::from(vec![Span::styled(prefix, theme.accent),@@ -1380,11 +1288,9 @@ fn render_search_bar((content_row[0].x + prefix_width).min(content_row[0].right().saturating_sub(1));(cx, content_row[0].y)} else {- let segments = state.search_query.graphemes();- let cursor = state.search_query.cursor();- let before_cursor: String = segments.into_iter().take(cursor).collect();- let before_cursor_width = crate::tui::text::width(&before_cursor) as u16;- let cx = (content_row[0].x + prefix_width + before_cursor_width)+ let cx = (content_row[0].x+ + prefix_width+ + state.search_query.cursor_column_offset() as u16).min(content_row[0].right().saturating_sub(1));(cx, content_row[0].y)};diff --git a/src/tui/state.rs b/src/tui/state.rsindex 1a10180..a778c53 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -754,10 +754,7 @@ impl AppState {self.active_browse_preset = None;self.active_addon_catalog = None;self.browse_metrics.clear();- self.poster_image = None;- self.poster_protocol = None;- self.failed_posters.clear();- self.in_flight_posters.clear();+ self.clear_poster_cache();self.result_scroll = 0;self.search_list_state.select(None);self.is_homepage_mode = false;@@ -1024,6 +1021,19 @@ impl AppState {};Some(pb)}+ pub fn clear_poster_cache(&mut self) {+ self.poster_image = None;+ self.poster_protocol = None;+ self.search_posters.clear();+ self.search_poster_protocols.clear();+ self.failed_posters.clear();+ self.in_flight_posters.clear();+ }++ pub fn clear_poster_protocols(&mut self) {+ self.poster_protocol = None;+ self.search_poster_protocols.clear();+ }}pub fn cycle_list_selection(state: &mut ListState, total_items: usize, forward: bool) {@@ -1047,6 +1057,21 @@ pub fn cycle_list_selection(state: &mut ListState, total_items: usize, forward:state.select(Some(next));}+pub fn step_list_selection(state: &mut ListState, total_items: usize, step: isize) {+ if total_items == 0 {+ state.select(None);+ return;+ }+ let max = total_items.saturating_sub(1);+ let cur = state.selected().unwrap_or(0);+ let next = if step < 0 {+ cur.saturating_sub(step.unsigned_abs())+ } else {+ (cur + step as usize).min(max)+ };+ state.select(Some(next));+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum TvManagerRow {Header(&'static str),@@ -1403,4 +1428,36 @@ mod tests {state.cycle_settings_player(false);assert_eq!(state.default_player.as_deref(), Some("mpv"));}+ #[test]+ fn test_step_list_selection() {+ let mut state = ListState::default();+ step_list_selection(&mut state, 0, 5);+ assert_eq!(state.selected(), None);++ step_list_selection(&mut state, 10, 5);+ assert_eq!(state.selected(), Some(5));++ step_list_selection(&mut state, 10, 10);+ assert_eq!(state.selected(), Some(9));++ step_list_selection(&mut state, 10, -3);+ assert_eq!(state.selected(), Some(6));++ step_list_selection(&mut state, 10, -20);+ assert_eq!(state.selected(), Some(0));+ }++ #[test]+ fn test_clear_poster_cache() {+ let mut state = AppState::default();+ state.in_flight_posters.insert("p1".to_string());+ state+ .failed_posters+ .put("p2".to_string(), std::time::Instant::now());+ state.clear_poster_cache();+ assert!(state.in_flight_posters.is_empty());+ assert!(state.failed_posters.is_empty());+ assert!(state.poster_image.is_none());+ assert!(state.poster_protocol.is_none());+ }}diff --git a/src/tui/text.rs b/src/tui/text.rsindex cea01fc..a75a900 100644--- a/src/tui/text.rs+++ b/src/tui/text.rs@@ -71,6 +71,29 @@ impl TextInputBuffer {.map(|(idx, _)| idx).unwrap_or(self.content.len())}+ pub fn cursor_prefix_str(&self) -> &str {+ &self.content[..self.cursor_byte_offset()]+ }++ pub fn cursor_column_offset(&self) -> usize {+ width(self.cursor_prefix_str())+ }++ pub fn cursor_split_parts(&self) -> (&str, &str, &str) {+ let cursor_byte = self.cursor_byte_offset();+ let before = &self.content[..cursor_byte];+ if cursor_byte >= self.content.len() {+ (before, " ", "")+ } else {+ let mut indices = self.content[cursor_byte..].grapheme_indices(true);+ if let Some((_, grapheme)) = indices.next() {+ let after_offset = cursor_byte + grapheme.len();+ (before, grapheme, &self.content[after_offset..])+ } else {+ (before, " ", "")+ }+ }+ }pub fn insert(&mut self, c: char) {let offset = self.cursor_byte_offset();@@ -800,4 +823,29 @@ mod tests {assert_eq!(extract_4digit_year("No year here"), "");assert_eq!(extract_4digit_year("Not A Year (20x4)"), "");}+ #[test]+ fn test_text_input_buffer_cursor_helpers() {+ let mut buf = TextInputBuffer::from_str("hello");+ assert_eq!(buf.cursor_prefix_str(), "hello");+ assert_eq!(buf.cursor_column_offset(), 5);+ assert_eq!(buf.cursor_split_parts(), ("hello", " ", ""));++ buf.set_cursor(2);+ assert_eq!(buf.cursor_prefix_str(), "he");+ assert_eq!(buf.cursor_column_offset(), 2);+ assert_eq!(buf.cursor_split_parts(), ("he", "l", "lo"));++ buf.set_cursor(0);+ assert_eq!(buf.cursor_prefix_str(), "");+ assert_eq!(buf.cursor_column_offset(), 0);+ assert_eq!(buf.cursor_split_parts(), ("", "h", "ello"));++ let mut cjk_buf = TextInputBuffer::from_str("电影");+ assert_eq!(cjk_buf.cursor_prefix_str(), "电影");+ assert_eq!(cjk_buf.cursor_column_offset(), 4);+ cjk_buf.set_cursor(1);+ assert_eq!(cjk_buf.cursor_prefix_str(), "电");+ assert_eq!(cjk_buf.cursor_column_offset(), 2);+ assert_eq!(cjk_buf.cursor_split_parts(), ("电", "影", ""));+ }}diff --git a/src/tui/widgets/mod.rs b/src/tui/widgets/mod.rsindex 62c29a6..859ee78 100644--- a/src/tui/widgets/mod.rs+++ b/src/tui/widgets/mod.rs@@ -1,6 +1,7 @@pub mod badge;pub mod input;pub mod modal;+pub mod poster;pub mod scrollbar;pub mod settings;@@ -9,4 +10,20 @@ pub use badge::{};pub use input::render_single_line_input;pub use modal::{ModalFrame, render_modal_footer};+pub use poster::render_poster_placeholder;pub use scrollbar::render_scrollbar;++const SPINNER_FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];++pub fn loading_spinner(tick_count: u64, basic_terminal: bool) -> &'static str {+ if basic_terminal {+ match (tick_count / 4) % 4 {+ 0 => "..",+ 1 => "...",+ 2 => "....",+ _ => "..",+ }+ } else {+ SPINNER_FRAMES[(tick_count as usize) % SPINNER_FRAMES.len()]+ }+}diff --git a/src/tui/widgets/poster.rs b/src/tui/widgets/poster.rsnew file mode 100644index 0000000..addf3a2--- /dev/null+++ b/src/tui/widgets/poster.rs@@ -0,0 +1,95 @@+use ratatui::{+ Frame,+ layout::{Alignment, Rect},+ widgets::{Block, Borders, Paragraph},+};++use crate::tui::theme::Theme;++pub fn render_poster_placeholder(+ frame: &mut Frame,+ area: Rect,+ theme: &Theme,+ basic_terminal: bool,+ is_in_flight: bool,+ tick: u64,+) {+ if area.width < 2 || area.height < 2 {+ return;+ }+ let border_type = crate::tui::overlay::border_type(basic_terminal);+ let border_style = if is_in_flight {+ theme.lavender+ } else {+ theme.surface1+ };+ let block = Block::default()+ .borders(Borders::ALL)+ .border_type(border_type)+ .border_style(border_style);+ let inner = block.inner(area);+ frame.render_widget(block, area);++ if inner.height == 0 || inner.width == 0 {+ return;+ }++ let pad_top = inner.height.saturating_sub(1) / 2;+ let text_area = Rect {+ x: inner.x,+ y: inner.y + pad_top,+ width: inner.width,+ height: 1.min(inner.height),+ };++ if is_in_flight {+ let dots = match (tick / 4) % 4 {+ 0 => "·",+ 1 => "··",+ 2 => "···",+ _ => "····",+ };+ let p = Paragraph::new(dots)+ .style(theme.lavender)+ .alignment(Alignment::Center);+ frame.render_widget(p, text_area);+ } else {+ let label = if inner.width >= 8 {+ if basic_terminal { "[No Art]" } else { "No Art" }+ } else if inner.width >= 6 {+ "No Art"+ } else {+ "·"+ };+ let p = Paragraph::new(label)+ .style(theme.overlay0)+ .alignment(Alignment::Center);+ frame.render_widget(p, text_area);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use ratatui::{Terminal, backend::TestBackend};++ #[test]+ fn test_render_poster_placeholder_dimensions() {+ let backend = TestBackend::new(20, 10);+ let mut terminal = Terminal::new(backend).unwrap();+ let theme = Theme::default();++ terminal+ .draw(|f| {+ render_poster_placeholder(f, Rect::new(0, 0, 1, 1), &theme, false, false, 0);+ })+ .unwrap();++ terminal+ .draw(|f| {+ render_poster_placeholder(f, Rect::new(0, 0, 15, 8), &theme, false, true, 4);+ render_poster_placeholder(f, Rect::new(0, 0, 15, 8), &theme, true, false, 0);+ })+ .unwrap();+ }+}diff --git a/tests/settings_hub.rs b/tests/settings_hub.rsindex 52e8a48..36bfdad 100644--- a/tests/settings_hub.rs+++ b/tests/settings_hub.rs@@ -378,3 +378,39 @@ fn test_expand_download_path() {Some(std::path::PathBuf::from("/tmp/moviebox_downloads")));}++#[tokio::test]+async fn test_settings_hub_clear_cache_activation_and_notification() {+ let mut app = App::new();+ app.handle_action(Action::ShowSettingsPopup).await;+ assert!(app.state().show_settings_popup);++ app.handle_action(Action::SelectSettingsCategory(+ SettingsCategory::StorageInfo,+ ))+ .await;+ assert_eq!(app.state().settings_category, SettingsCategory::StorageInfo);+ assert_eq!(app.state().settings_selected_row, 0);++ app.handle_action(Action::SettingsActivateRow).await;+ let clearing = app.state().notifications.back();+ assert_eq!(clearing.map(|n| n.title.as_str()), Some("Clearing Cache"));++ app.handle_action(Action::ClearCache).await;+ assert!(!app.state().show_settings_popup);+ assert_eq!(+ app.state().active_screen,+ moviebox_tui::tui::state::Screen::Home+ );++ app.handle_action(Action::CacheCleared(Ok(()))).await;+ let notification = app.state().notifications.back();+ assert!(notification.is_some());+ assert_eq!(notification.unwrap().title, "Cache Cleared");++ app.handle_action(Action::CacheCleared(Err("filesystem error".to_string())))+ .await;+ let err_notification = app.state().notifications.back();+ assert!(err_notification.is_some());+ assert_eq!(err_notification.unwrap().title, "Cache Clear Failed");+}