Skip to content

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

feat(ux): add subtitle auto-selection, direct history resume, and non-destructive search navigation

Samir Hossains9ae93227299d
diff --git a/src/config.rs b/src/config.rs
index ab3c002..092ef29 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -18,8 +18,9 @@ pub struct Config {
pub addons_enabled: bool,
pub default_player: Option<String>,
pub download_dir: Option<String>,
+ pub preferred_subtitle_language: Option<String>,
+ pub auto_load_subtitles: bool,
}
-
impl Default for Config {
fn default() -> Self {
Self {
@@ -34,6 +35,8 @@ impl Default for Config {
addons_enabled: false,
default_player: None,
download_dir: None,
+ preferred_subtitle_language: Some("English".to_string()),
+ auto_load_subtitles: true,
}
}
}
@@ -150,3 +153,26 @@ pub fn save_addons(addons: &[InstalledAddon]) {
log::warn!("failed to write addons config: {error}");
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn config_defaults_and_serde() {
+ let config = Config::default();
+ assert_eq!(
+ config.preferred_subtitle_language.as_deref(),
+ Some("English")
+ );
+ assert!(config.auto_load_subtitles);
+
+ let json = serde_json::to_string(&config).expect("serialize");
+ let deserialized: Config = serde_json::from_str(&json).expect("deserialize");
+ assert_eq!(
+ deserialized.preferred_subtitle_language,
+ config.preferred_subtitle_language
+ );
+ assert_eq!(deserialized.auto_load_subtitles, config.auto_load_subtitles);
+ }
+}
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 138e3b1..f447072 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -81,8 +81,27 @@ impl App {
return None;
}
} else if !self.state.addon_input_active && !self.state.tv_input_active {
+ if let KeyCode::Char('u') = key.code {
+ if self.state.active_screen == Screen::Home {
+ self.state.clear_search_state();
+ self.state.input_mode = InputMode::Normal;
+ self.state.set_status_default("Search cleared.");
+ return None;
+ }
+ }
return None;
}
+ if let KeyCode::Char('u') = key.code {
+ if self.state.active_screen == Screen::Home
+ && !self.state.addon_input_active
+ && !self.state.tv_input_active
+ {
+ self.state.clear_search_state();
+ self.state.input_mode = InputMode::Normal;
+ self.state.set_status_default("Search cleared.");
+ return None;
+ }
+ }
}
if let KeyCode::Char('x') | KeyCode::Char('X') = key.code
@@ -304,10 +323,9 @@ impl App {
InputMode::Editing => {
if key.modifiers.contains(KeyModifiers::CONTROL) {
if let KeyCode::Char('u') = key.code {
- self.state.search_query.clear();
- self.state.suggest_index = None;
- self.state.search_suggestions.clear();
- self.state.last_search_edit = std::time::Instant::now();
+ self.state.clear_search_state();
+ self.state.input_mode = InputMode::Normal;
+ self.state.set_status_default("Search cleared.");
return None;
}
if let KeyCode::Char('w') = key.code {
@@ -323,10 +341,8 @@ impl App {
self.state.input_mode = InputMode::Normal;
self.state.suggest_index = None;
self.state.search_suggestions.clear();
- if self.state.search_query.starts_with('/')
- || self.state.search_results.is_empty()
- {
- self.state.search_query.clear();
+ if self.state.search_results.is_empty() {
+ self.state.clear_search_state();
}
self.state.set_status_default("");
}
@@ -893,6 +909,16 @@ impl App {
{
self.action_sender.send(Action::ToggleFavorite).ok();
}
+ KeyCode::Char(' ') | KeyCode::Char('p') | KeyCode::Char('P')
+ if self
+ .state
+ .search_query
+ .trim()
+ .eq_ignore_ascii_case("/history")
+ && !self.state.search_results.is_empty() =>
+ {
+ self.resume_history_playback();
+ }
KeyCode::Char(c)
if (key.modifiers.is_empty()
|| key.modifiers == KeyModifiers::SHIFT) =>
@@ -959,6 +985,33 @@ impl App {
self.action_sender.send(Action::GoBack).ok();
}
}
+ KeyCode::Char(' ') | KeyCode::Char('p') | KeyCode::Char('P') => {
+ if !self.state.subtitle_popup
+ && !self.state.player_picker_popup
+ && !self.state.show_season_download_confirm
+ && !self.state.show_episode_download_confirm
+ {
+ let open_with = key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::SHIFT);
+ match self.state.details_pane {
+ crate::tui::state::DetailsPane::Streams => {
+ self.action_sender.send(Action::PlayStream(open_with)).ok();
+ }
+ crate::tui::state::DetailsPane::Seasons => {
+ self.trigger_episode_fetch();
+ }
+ crate::tui::state::DetailsPane::Episodes => {
+ self.trigger_episode_fetch();
+ }
+ crate::tui::state::DetailsPane::Languages => {
+ let idx =
+ self.state.language_list_state.selected().unwrap_or(0);
+ self.action_sender.send(Action::SelectLanguage(idx)).ok();
+ }
+ }
+ }
+ }
KeyCode::Char('q') => {
self.action_sender.send(Action::Quit).ok();
}
diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs
index 948867c..39c2801 100644
--- a/src/tui/app/mod.rs
+++ b/src/tui/app/mod.rs
@@ -77,6 +77,8 @@ impl App {
state.active_theme_kind = config.active_theme;
state.default_player = config.default_player;
state.download_dir = config.download_dir.map(std::path::PathBuf::from);
+ state.preferred_subtitle_language = config.preferred_subtitle_language;
+ state.auto_load_subtitles = config.auto_load_subtitles;
state.installed_addons = crate::config::load_addons();
let env_theme = std::env::var("MOVIEBOX_THEME")
@@ -168,6 +170,8 @@ impl App {
.download_dir
.as_ref()
.map(|p| p.to_string_lossy().to_string()),
+ preferred_subtitle_language: self.state.preferred_subtitle_language.clone(),
+ auto_load_subtitles: self.state.auto_load_subtitles,
};
crate::tui::config::save(&config);
}
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index 3dbea5a..1540f59 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -1,6 +1,9 @@
use super::App;
use crate::providers::models::{ProviderKind, Release};
-use crate::tui::{action::Action, state::Screen};
+use crate::tui::{
+ action::Action,
+ state::{InputMode, Screen},
+};
impl App {
fn remember_player_preference(&mut self, player: crate::tui::state::PlayerKind) {
@@ -414,6 +417,13 @@ impl App {
}
match self.state.active_screen {
Screen::Home => {
+ if !self.state.search_results.is_empty() {
+ self.state.input_mode = InputMode::Editing;
+ self.state.favorites_focus = false;
+ self.state.favorites_landing_state.select(None);
+ self.state.last_search_edit = std::time::Instant::now();
+ return None;
+ }
self.state.is_loading = false;
self.state.active_search_request =
self.state.active_search_request.wrapping_add(1);
@@ -421,20 +431,7 @@ impl App {
self.state.active_homepage_request.wrapping_add(1);
self.state.active_preview_request =
self.state.active_preview_request.wrapping_add(1);
- self.state.search_poster_protocols.clear();
- self.state.search_results.clear();
- self.state.active_browse_preset = None;
- self.state.active_addon_catalog = None;
- self.state.browse_metrics.clear();
- self.state.search_error = None;
- self.state.search_query.clear();
- self.state.search_suggestions.clear();
- self.state.suggest_index = None;
- self.state.search_preview = None;
- self.state.preview_loading = false;
- self.state.poster_image = None;
- self.state.poster_protocol = None;
- self.state.search_list_state.select(None);
+ self.state.clear_search_state();
self.state.set_status_default("Search cleared.");
}
Screen::Details => {
@@ -856,8 +853,31 @@ impl App {
self.state.stream_error = None;
self.state.resource_list_state.select(None);
self.state.language_list_state.select(Some(0));
- self.state.season_list_state.select(Some(0));
- self.state.episode_list_state.select(Some(0));
+
+ let is_history = self
+ .state
+ .search_query
+ .trim()
+ .eq_ignore_ascii_case("/history")
+ || (item.season > 0 && item.episode > 0);
+ let se = if is_history && item.season > 0 {
+ item.season
+ } else {
+ 1
+ };
+ let ep = if is_history && item.episode > 0 {
+ item.episode
+ } else {
+ 1
+ };
+ self.state.selected_season = se;
+ self.state.selected_episode = ep;
+ self.state
+ .season_list_state
+ .select(Some(se.saturating_sub(1)));
+ self.state
+ .episode_list_state
+ .select(Some(ep.saturating_sub(1)));
self.state.language_chosen = false;
if let Some(cached) = self
.state
@@ -884,4 +904,83 @@ impl App {
}
None
}
+
+ pub(super) fn resume_history_playback(&mut self) {
+ if self.state.is_loading {
+ return;
+ }
+ if self.state.last_search_edit.elapsed().as_millis() < 500 {
+ return;
+ }
+ let idx_opt = self.state.search_list_state.selected();
+ let item_opt = idx_opt.and_then(|idx| self.state.search_results.get(idx).cloned());
+ if let Some(item) = item_opt {
+ if self.state.is_tv_mode || item.stype == 3 {
+ self.action_sender
+ .send(Action::LaunchMpv(item.id.clone(), None))
+ .ok();
+ return;
+ }
+ self.state.active_screen = Screen::Details;
+ self.state.active_subject_id = Some(item.id.clone());
+ let mut fallback_details = serde_json::json!({
+ "id": item.id,
+ "subjectId": item.id,
+ "title": item.title,
+ "subjectType": item.stype,
+ "releaseDate": item.release_year,
+ "cover": { "url": item.cover_url },
+ });
+ if let Some(preview) = &self.state.search_preview {
+ if let Some(preview_obj) = preview.as_object() {
+ if let Some(fallback_obj) = fallback_details.as_object_mut() {
+ for (k, v) in preview_obj {
+ if !fallback_obj.contains_key(k) || fallback_obj[k].is_null() {
+ fallback_obj.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ }
+ }
+ self.state.selected_details = Some(fallback_details);
+ self.state.selected_resources = None;
+ self.state.is_loading = true;
+ self.state.is_fetching_streams = false;
+ self.state.stream_error = None;
+ self.state.resource_list_state.select(None);
+ self.state.language_list_state.select(Some(0));
+
+ let se = if item.season > 0 { item.season } else { 1 };
+ let ep = if item.episode > 0 { item.episode } else { 1 };
+ self.state.selected_season = se;
+ self.state.selected_episode = ep;
+ self.state
+ .season_list_state
+ .select(Some(se.saturating_sub(1)));
+ self.state
+ .episode_list_state
+ .select(Some(ep.saturating_sub(1)));
+
+ self.state.auto_play_on_ready = true;
+ self.state.language_chosen = false;
+ if let Some(cached) = self
+ .state
+ .image_cache
+ .get(&item.id)
+ .or_else(|| self.state.search_posters.get(&item.id))
+ {
+ self.state.poster_image = Some(std::sync::Arc::clone(cached));
+ } else {
+ self.state.poster_image = None;
+ }
+ self.state.available_seasons.clear();
+ self.state
+ .set_status_default(format!("Resuming playback for {}...", item.title));
+
+ let sender = self.action_sender.clone();
+ sender
+ .send(Action::FetchDetails(item.id.clone(), false))
+ .ok();
+ }
+ }
}
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index 8d609ab..ba56fd6 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -514,6 +514,26 @@ impl App {
self.state.is_resolving_playback = false;
let options = crate::tui::state::caption_options(&ext_captions);
+ if self.state.auto_load_subtitles {
+ if let Some(preferred) = &self.state.preferred_subtitle_language {
+ let pref_lower = preferred.to_lowercase();
+ if let Some((_, sub_url)) = options.iter().find(|(name, url)| {
+ !url.is_empty() && name.to_lowercase().contains(&pref_lower)
+ }) {
+ if open_with {
+ self.action_sender
+ .send(Action::ShowPlayerPicker(link, Some(sub_url.clone())))
+ .ok();
+ } else {
+ self.action_sender
+ .send(Action::LaunchMpv(link, Some(sub_url.clone())))
+ .ok();
+ }
+ return None;
+ }
+ }
+ }
+
if options.len() > 1 {
self.state.show_help = false;
self.state.player_picker_popup = false;
@@ -722,4 +742,59 @@ mod tests {
"Player exited unsuccessfully without error output."
);
}
+
+ #[tokio::test]
+ async fn auto_select_matching_preferred_subtitle() {
+ let mut app = crate::tui::app::App::new();
+ app.state.auto_load_subtitles = true;
+ app.state.preferred_subtitle_language = Some("English".to_string());
+
+ let ext_captions = serde_json::json!({
+ "extCaptions": [
+ { "lanName": "Spanish", "url": "https://example.com/es.srt" },
+ { "lanName": "English (Full)", "url": "https://example.com/en.srt" }
+ ]
+ });
+
+ app.handle_playback(crate::tui::action::Action::ShowSubtitlePopup(
+ "https://example.com/video.mp4".to_string(),
+ ext_captions,
+ false,
+ ))
+ .await;
+
+ assert!(!app.state.subtitle_popup);
+ let action = app.action_receiver.recv().await;
+ assert!(matches!(
+ action,
+ Some(crate::tui::action::Action::LaunchMpv(
+ link,
+ Some(sub)
+ )) if link == "https://example.com/video.mp4" && sub == "https://example.com/en.srt"
+ ));
+ }
+
+ #[tokio::test]
+ async fn show_popup_when_auto_load_subtitles_disabled_or_no_match() {
+ let mut app = crate::tui::app::App::new();
+ app.state.auto_load_subtitles = false;
+ app.state.preferred_subtitle_language = Some("English".to_string());
+
+ let ext_captions = serde_json::json!({
+ "extCaptions": [
+ { "lanName": "Spanish", "url": "https://example.com/es.srt" },
+ { "lanName": "French", "url": "https://example.com/fr.srt" }
+ ]
+ });
+
+ app.handle_playback(crate::tui::action::Action::ShowSubtitlePopup(
+ "https://example.com/video.mp4".to_string(),
+ ext_captions,
+ false,
+ ))
+ .await;
+
+ assert!(app.state.subtitle_popup);
+ assert_eq!(app.state.subtitle_list.len(), 3);
+ }
}
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 3193cdd..e5c2246 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -908,6 +908,7 @@ impl App {
return None;
}
self.state.is_loading = false;
+ self.state.details_error = None;
let mut final_payload = payload.clone();
if self.state.language_chosen {
if let Some(existing) = &self.state.selected_details {
@@ -1152,18 +1153,16 @@ impl App {
default_episode = history.episode;
}
- let target_season = if self.state.language_chosen && self.state.selected_season > 0
- {
+ let target_season = if self.state.selected_season > 0 {
self.state.selected_season
} else {
default_season
};
- let target_episode =
- if self.state.language_chosen && self.state.selected_episode > 0 {
- self.state.selected_episode
- } else {
- default_episode
- };
+ let target_episode = if self.state.selected_episode > 0 {
+ self.state.selected_episode
+ } else {
+ default_episode
+ };
let season_idx = self
.state
@@ -1229,7 +1228,10 @@ impl App {
.and_then(|d| d.as_array())
.is_some_and(|a| a.len() > 1);
- if has_multiple_dubs && !self.state.language_chosen {
+ if has_multiple_dubs
+ && !self.state.language_chosen
+ && !self.state.auto_play_on_ready
+ {
self.state.details_pane = crate::tui::state::DetailsPane::Languages;
self.state.is_loading = false;
self.state
@@ -1254,6 +1256,7 @@ impl App {
if request_id != self.state.active_details_request {
return None;
}
+ self.state.auto_play_on_ready = false;
if !self.context_is_current(context) {
return None;
}
@@ -1271,6 +1274,7 @@ impl App {
}
self.state.is_fetching_streams = false;
self.state.stream_error = None;
+ self.state.details_error = Some(err.clone());
self.state
.set_status_default(format!("Details fetch failed: {}", err));
@@ -1397,6 +1401,10 @@ impl App {
}
self.state.is_loading = false;
self.state.is_fetching_streams = false;
+ if self.state.auto_play_on_ready {
+ self.state.auto_play_on_ready = false;
+ self.action_sender.send(Action::PlayStream(false)).ok();
+ }
return None;
}
@@ -2010,6 +2018,10 @@ impl App {
self.action_sender.send(Action::DownloadStream(None)).ok();
}
+ if self.state.auto_play_on_ready {
+ self.state.auto_play_on_ready = false;
+ self.action_sender.send(Action::PlayStream(false)).ok();
+ }
}
Action::EpisodeStreamsFailed(
@@ -2033,6 +2045,7 @@ impl App {
{
return None;
}
+ self.state.auto_play_on_ready = false;
self.state.is_loading = false;
self.state.is_fetching_streams = false;
self.state.selected_resources = None;
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index cd90d5c..eeee0c6 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -132,6 +132,12 @@ impl App {
self.action_sender.send(Action::ClearCache).ok();
Some(true)
}
+ crate::tui::commands::ParsedCommand::Clear => {
+ self.state.clear_search_state();
+ self.state.input_mode = InputMode::Normal;
+ self.state.set_status_default("Search cleared.");
+ Some(true)
+ }
crate::tui::commands::ParsedCommand::Github => {
let _ = open::that("https://github.com/mesamirh/MovieBox-Tui");
self.state.search_query.clear();
@@ -662,6 +668,7 @@ impl App {
self.state.active_subject_id = Some(id.to_string());
self.state.poster_protocol = None;
self.state.is_loading = true;
+ self.state.details_error = None;
self.state.active_details_request = self.state.active_details_request.wrapping_add(1);
self.state
.fetch_cancel
diff --git a/src/tui/commands.rs b/src/tui/commands.rs
index d2072f0..b048145 100644
--- a/src/tui/commands.rs
+++ b/src/tui/commands.rs
@@ -12,6 +12,7 @@ pub enum SlashCommand {
Update,
ToggleUpdate,
ClearCache,
+ Clear,
Github,
ToggleBdix,
ToggleStreaming,
@@ -32,6 +33,7 @@ pub enum ParsedCommand<'a> {
Update,
ToggleUpdate,
ClearCache,
+ Clear,
Github,
ToggleBdix,
ToggleStreaming,
@@ -41,7 +43,7 @@ pub enum ParsedCommand<'a> {
}
impl SlashCommand {
- pub const ALL: [Self; 16] = [
+ pub const ALL: [Self; 17] = [
Self::Browse,
Self::History,
Self::Favorites,
@@ -52,6 +54,7 @@ impl SlashCommand {
Self::Update,
Self::ToggleUpdate,
Self::ClearCache,
+ Self::Clear,
Self::Github,
Self::ToggleBdix,
Self::ToggleStreaming,
@@ -72,6 +75,7 @@ impl SlashCommand {
Self::Update => "/update",
Self::ToggleUpdate => "/toggle-update",
Self::ClearCache => "/clear-cache",
+ Self::Clear => "/clear",
Self::Github => "/github",
Self::ToggleBdix => "/toggle-bdix",
Self::ToggleStreaming => "/toggle-streaming",
@@ -99,6 +103,7 @@ impl SlashCommand {
Self::Update => "Check for newer release",
Self::ToggleUpdate => "Toggle automatic update checks",
Self::ClearCache => "Clear cached data",
+ Self::Clear => "Clear search results and return to landing",
Self::Github => "Open project repository",
Self::ToggleBdix => "Toggle BDIX FTP sources",
Self::ToggleStreaming => "Toggle Streaming mode navigation",
@@ -133,6 +138,7 @@ impl SlashCommand {
| Self::Update
| Self::ToggleUpdate
| Self::ClearCache
+ | Self::Clear
| Self::Github
| Self::Probe => true,
}
@@ -206,6 +212,7 @@ impl SlashCommand {
"/update" => Some(ParsedCommand::Update),
"/toggle-update" => Some(ParsedCommand::ToggleUpdate),
"/clear-cache" => Some(ParsedCommand::ClearCache),
+ "/clear" => Some(ParsedCommand::Clear),
"/github" => Some(ParsedCommand::Github),
"/toggle-bdix" | "/enable-bdix" | "/disable-bdix" => Some(ParsedCommand::ToggleBdix),
"/toggle-streaming" | "/enable-streaming" | "/disable-streaming" => {
@@ -312,8 +319,10 @@ mod tests {
#[test]
fn test_toggle_commands_and_aliases_parse() {
let state = AppState::default();
- assert_eq!(SlashCommand::ALL.len(), 16);
-
+ assert_eq!(SlashCommand::ALL.len(), 17);
+ assert_eq!(SlashCommand::parse("/clear"), Some(ParsedCommand::Clear));
+ assert!(SlashCommand::Clear.is_available(&state));
+ assert_eq!(SlashCommand::Clear.name(), "/clear");
assert_eq!(
SlashCommand::parse("/toggle-tv"),
Some(ParsedCommand::ToggleTv)
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index ef78147..258f0c2 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -105,6 +105,43 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let details_json = match &state.selected_details {
Some(d) => d,
None => {
+ if let Some(err) = &state.details_error {
+ let box_width = area.width.saturating_sub(4).clamp(30, 60).min(area.width);
+ let box_height = area.height.saturating_sub(2).clamp(5, 7).min(area.height);
+ let x = area.x + (area.width.saturating_sub(box_width)) / 2;
+ let y = area.y + (area.height.saturating_sub(box_height)) / 2;
+ let error_area = Rect::new(x, y, box_width, box_height);
+
+ let error_block = Block::default()
+ .borders(Borders::ALL)
+ .border_type(crate::tui::overlay::border_type(state.basic_terminal))
+ .border_style(theme.error)
+ .title(Line::from(vec![Span::styled(
+ " Error Loading Details ",
+ theme.error.add_modifier(Modifier::BOLD),
+ )]));
+
+ let err_msg =
+ crate::tui::text::truncate_width(err, (box_width.saturating_sub(4)) as usize);
+ let text = vec![
+ Line::from(""),
+ Line::from(Span::styled(err_msg, theme.text)),
+ Line::from(""),
+ Line::from(vec![
+ crate::tui::overlay::key_hint("r", "Retry fetch", theme),
+ Span::raw(" "),
+ crate::tui::overlay::key_hint("Esc", "Back", theme),
+ ]),
+ ];
+
+ let error_p = Paragraph::new(text)
+ .block(error_block)
+ .alignment(Alignment::Center);
+
+ frame.render_widget(error_p, error_area);
+ return;
+ }
+
let spinner = stream_loading_spinner(state.tick_count, state.basic_terminal);
let vertical_chunks = Layout::default()
@@ -506,11 +543,26 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let meta_p = Paragraph::new(top_meta).wrap(Wrap { trim: true });
frame.render_widget(meta_p, meta_chunks[0]);
- let synopsis_capacity =
- (meta_chunks[1].width as usize).saturating_mul(meta_chunks[1].height as usize);
- let synopsis = truncate_with_ellipsis(intro, synopsis_capacity);
- let syn_lines = vec![Line::from(vec![Span::styled(synopsis, theme.subtext1)])];
- let intro_p = Paragraph::new(syn_lines).wrap(Wrap { trim: true });
+ let max_width = meta_chunks[1].width as usize;
+ let max_lines = meta_chunks[1].height as usize;
+ let mut wrapped = crate::tui::text::wrap_text(intro, max_width);
+ if wrapped.len() > max_lines {
+ wrapped.truncate(max_lines);
+ if let Some(last) = wrapped.last_mut() {
+ let ellipsis = if state.basic_terminal { "..." } else { "…" };
+ let ellipsis_w = crate::tui::text::width(ellipsis);
+ if max_width >= ellipsis_w {
+ let trimmed =
+ crate::tui::text::truncate_width(last, max_width.saturating_sub(ellipsis_w));
+ *last = format!("{trimmed}{ellipsis}");
+ }
+ }
+ }
+ let syn_lines: Vec<Line> = wrapped
+ .into_iter()
+ .map(|line| Line::from(vec![Span::styled(line, theme.subtext1)]))
+ .collect();
+ let intro_p = Paragraph::new(syn_lines);
frame.render_widget(intro_p, meta_chunks[1]);
let has_languages = if let Some(dubs) = details_json.get("dubs").and_then(|d| d.as_array()) {
@@ -1390,22 +1442,6 @@ fn selected_stream_summary(state: &AppState) -> Option<String> {
(!fields.is_empty()).then(|| fields.join(" · "))
}
-fn truncate_with_ellipsis(value: &str, capacity: usize) -> String {
- if capacity == 0 {
- return String::new();
- }
- if crate::tui::text::width(value) <= capacity {
- return value.to_string();
- }
- if capacity == 1 {
- return "…".to_string();
- }
- format!(
- "{}…",
- crate::tui::text::truncate_width(value, capacity.saturating_sub(1))
- )
-}
-
fn clean_language_name(value: &str) -> String {
let mut name = if value.to_ascii_lowercase().starts_with("original") {
"Original".to_string()
@@ -2132,4 +2168,51 @@ mod tests {
let basic_spans = render_media_tag_spans(&tags, &theme, true);
assert_eq!(basic_spans[0].content, "[HDR] ");
}
+
+ #[test]
+ fn test_details_error_state_rendering() {
+ let backend = ratatui::backend::TestBackend::new(80, 24);
+ let mut terminal = ratatui::Terminal::new(backend).unwrap();
+ let mut state = AppState {
+ details_error: Some("Failed to fetch details: network timeout".to_string()),
+ ..Default::default()
+ };
+ let theme = Theme::mocha();
+
+ terminal
+ .draw(|frame| {
+ draw(frame, frame.area(), &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let content = buffer
+ .content()
+ .iter()
+ .map(|cell| cell.symbol())
+ .collect::<String>();
+ assert!(content.contains("Error Loading Details"));
+ assert!(content.contains("Retry fetch"));
+ assert!(content.contains("Back"));
+ }
+
+ #[test]
+ fn test_synopsis_wrap_clamping() {
+ let backend = ratatui::backend::TestBackend::new(80, 24);
+ let mut terminal = ratatui::Terminal::new(backend).unwrap();
+ let mut state = AppState {
+ selected_details: Some(serde_json::json!({
+ "title": "Test Movie",
+ "description": "A very long synopsis that will definitely exceed the single line boundary and should be clamped cleanly with an ellipsis without overflowing the paragraph bounds."
+ })),
+ ..Default::default()
+ };
+ let theme = Theme::mocha();
+
+ terminal
+ .draw(|frame| {
+ draw(frame, frame.area(), &mut state, &theme);
+ })
+ .unwrap();
+ }
}
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 39ad91b..30ac57b 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -237,26 +237,22 @@ fn render_search_state(
}
let card_width = area.width.min(64);
- let card = Rect {
- x: area.x + area.width.saturating_sub(card_width) / 2,
- y: area.y + area.height.saturating_sub(3) / 2,
- width: card_width,
- height: 3,
- };
- let rows = Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(1),
- Constraint::Length(1),
- Constraint::Length(1),
- ])
- .split(card);
-
let query = crate::tui::text::truncate_width(
&state.search_query,
card_width.saturating_sub(10) as usize,
);
- let line = match view {
+
+ let ctrl_p = crate::tui::text::ctrl_key("P");
+ let ctrl_u = crate::tui::text::ctrl_key("U");
+ let bullet = if state.basic_terminal {
+ " - "
+ } else {
+ " • "
+ };
+
+ let mut lines: Vec<Line> = Vec::new();
+
+ match view {
SearchViewState::Loading => {
let msg = if state.basic_terminal {
let dots = match (state.tick_count / 4) % 3 {
@@ -292,7 +288,7 @@ fn render_search_state(
format!("{spinner} Loading")
}
};
- Line::from(vec![Span::styled(msg, theme.lavender)])
+ lines.push(Line::from(vec![Span::styled(msg, theme.lavender)]));
}
SearchViewState::NoResults => {
let symbol = if state.basic_terminal { "-" } else { "·" };
@@ -307,10 +303,27 @@ fn render_search_state(
} else {
"No results found".to_string()
};
- Line::from(vec![
+ lines.push(Line::from(vec![
Span::styled(format!("{symbol} "), theme.text_dim),
Span::styled(msg, theme.text),
- ])
+ ]));
+ lines.push(Line::from(""));
+ lines.push(Line::from(vec![
+ Span::styled("[", theme.text_dim),
+ Span::styled(&ctrl_p, theme.shortcut),
+ Span::styled("] ", theme.text_dim),
+ Span::styled("Switch provider", theme.text_dim),
+ Span::styled(bullet, theme.text_dim),
+ Span::styled("[", theme.text_dim),
+ Span::styled("/browse", theme.shortcut),
+ Span::styled("] ", theme.text_dim),
+ Span::styled("Browse categories", theme.text_dim),
+ Span::styled(bullet, theme.text_dim),
+ Span::styled("[", theme.text_dim),
+ Span::styled(&ctrl_u, theme.shortcut),
+ Span::styled("] ", theme.text_dim),
+ Span::styled("Clear", theme.text_dim),
+ ]));
}
SearchViewState::Error => {
let symbol = if state.basic_terminal { "!" } else { "×" };
@@ -321,23 +334,59 @@ fn render_search_state(
"Search request failed"
}
});
- Line::from(vec![
- Span::styled(format!("{symbol} "), theme.error),
- Span::styled(
- crate::tui::text::truncate_width(
- err_text,
- card_width.saturating_sub(4) as usize,
- ),
- theme.error,
- ),
- ])
+ let wrap_width = card_width.saturating_sub(6).max(10) as usize;
+ let wrapped_err_lines = crate::tui::text::wrap_text(err_text, wrap_width);
+ if wrapped_err_lines.is_empty() {
+ lines.push(Line::from(vec![
+ Span::styled(format!("{symbol} "), theme.error),
+ Span::styled("Search request failed", theme.error),
+ ]));
+ } else {
+ for (idx, eline) in wrapped_err_lines.into_iter().enumerate() {
+ if idx == 0 {
+ lines.push(Line::from(vec![
+ Span::styled(format!("{symbol} "), theme.error),
+ Span::styled(eline, theme.error),
+ ]));
+ } else {
+ lines.push(Line::from(vec![
+ Span::styled(" ", theme.error),
+ Span::styled(eline, theme.error),
+ ]));
+ }
+ }
+ }
+ lines.push(Line::from(""));
+ lines.push(Line::from(vec![
+ Span::styled("[", theme.text_dim),
+ Span::styled("r", theme.shortcut),
+ Span::styled("] ", theme.text_dim),
+ Span::styled("Retry request", theme.text_dim),
+ Span::styled(bullet, theme.text_dim),
+ Span::styled("[", theme.text_dim),
+ Span::styled(&ctrl_p, theme.shortcut),
+ Span::styled("] ", theme.text_dim),
+ Span::styled("Switch provider", theme.text_dim),
+ Span::styled(bullet, theme.text_dim),
+ Span::styled("[", theme.text_dim),
+ Span::styled("Esc", theme.shortcut),
+ Span::styled("] ", theme.text_dim),
+ Span::styled("Back", theme.text_dim),
+ ]));
}
_ => return,
};
- frame.render_widget(Paragraph::new(line).alignment(Alignment::Center), rows[1]);
-}
+ let card_height = (lines.len() as u16).min(area.height);
+ let card = Rect {
+ x: area.x + area.width.saturating_sub(card_width) / 2,
+ y: area.y + area.height.saturating_sub(card_height) / 2,
+ width: card_width,
+ height: card_height,
+ };
+ frame.render_widget(Paragraph::new(lines).alignment(Alignment::Center), card);
+}
fn render_favorites_landing(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
if area.height < 2 || area.width < 20 {
return;
diff --git a/src/tui/state.rs b/src/tui/state.rs
index a0e2970..acfe785 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -91,8 +91,10 @@ pub struct AppState {
pub show_episode_download_confirm: bool,
pub episode_download_confirm_yes_selected: bool,
pub is_waiting_for_download_stream: bool,
+ pub auto_play_on_ready: bool,
pub is_fetching_streams: bool,
pub stream_error: Option<String>,
+ pub details_error: Option<String>,
pub preview_cache: lru::LruCache<String, serde_json::Value>,
pub resource_list_state: ListState,
@@ -187,6 +189,8 @@ pub struct AppState {
pub subtitle_list_state: ListState,
pub pending_play_link: Option<String>,
pub pending_open_with: bool,
+ pub preferred_subtitle_language: Option<String>,
+ pub auto_load_subtitles: bool,
pub basic_terminal: bool,
pub bdix_enabled: bool,
pub streaming_enabled: bool,
@@ -249,7 +253,9 @@ impl Default for AppState {
episode_download_confirm_yes_selected: false,
is_waiting_for_download_stream: false,
is_fetching_streams: false,
+ auto_play_on_ready: false,
stream_error: None,
+ details_error: None,
preview_cache: lru::LruCache::new(cache_capacity(30)),
resource_list_state: ListState::default(),
@@ -340,6 +346,8 @@ impl Default for AppState {
subtitle_list_state: ListState::default(),
pending_play_link: None,
pending_open_with: false,
+ preferred_subtitle_language: Some("English".to_string()),
+ auto_load_subtitles: true,
bdix_enabled: false,
streaming_enabled: true,
is_tv_mode: false,
@@ -567,7 +575,9 @@ impl AppState {
self.selected_resources = None;
self.is_fetching_streams = false;
self.pending_episode_fetch = None;
+ self.auto_play_on_ready = false;
self.stream_error = None;
+ self.details_error = None;
self.available_seasons.clear();
self.available_episode_numbers.clear();
self.season_list_state.select(None);
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index 673f862..7be5e40 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -502,3 +502,207 @@ async fn test_contextual_window_title() {
}));
assert_eq!(app.contextual_title(), "MovieBox-Tui — Inception");
}
+#[tokio::test]
+async fn test_esc_in_normal_mode_focuses_search_bar_when_results_present() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Normal;
+ app.state_mut().search_query.set_content("matrix");
+ app.state_mut().search_results.push(SearchResult {
+ id: "1".to_string(),
+ title: "The Matrix".to_string(),
+ stype: 1,
+ release_year: "1999".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: ProviderKind::MovieBox,
+ });
+ app.state_mut().search_list_state.select(Some(0));
+
+ let esc_key = KeyEvent::new(KeyCode::Esc, KeyModifiers::empty());
+ app.handle_action(Action::Key(esc_key)).await;
+ app.handle_action(Action::GoBack).await;
+
+ assert_eq!(app.state().input_mode, InputMode::Editing);
+ assert_eq!(app.state().search_results.len(), 1);
+ assert_eq!(app.state().search_query, "matrix");
+}
+
+#[tokio::test]
+async fn test_esc_in_editing_mode_switches_to_normal_when_results_present() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Editing;
+ app.state_mut().search_query.set_content("matrix");
+ app.state_mut().search_results.push(SearchResult {
+ id: "1".to_string(),
+ title: "The Matrix".to_string(),
+ stype: 1,
+ release_year: "1999".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: ProviderKind::MovieBox,
+ });
+
+ let esc_key = KeyEvent::new(KeyCode::Esc, KeyModifiers::empty());
+ app.handle_action(Action::Key(esc_key)).await;
+
+ assert_eq!(app.state().input_mode, InputMode::Normal);
+ assert_eq!(app.state().search_results.len(), 1);
+ assert_eq!(app.state().search_query, "matrix");
+}
+
+#[tokio::test]
+async fn test_esc_in_editing_mode_clears_when_no_results() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Editing;
+ app.state_mut().search_query.set_content("matrix");
+ assert!(app.state().search_results.is_empty());
+
+ let esc_key = KeyEvent::new(KeyCode::Esc, KeyModifiers::empty());
+ app.handle_action(Action::Key(esc_key)).await;
+
+ assert_eq!(app.state().input_mode, InputMode::Normal);
+ assert!(app.state().search_query.is_empty());
+}
+
+#[tokio::test]
+async fn test_ctrl_u_and_clear_command_clears_results_cleanly() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Editing;
+ app.state_mut().search_query.set_content("matrix");
+ app.state_mut().search_results.push(SearchResult {
+ id: "1".to_string(),
+ title: "The Matrix".to_string(),
+ stype: 1,
+ release_year: "1999".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: ProviderKind::MovieBox,
+ });
+
+ let ctrl_u = KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL);
+ app.handle_action(Action::Key(ctrl_u)).await;
+
+ assert!(app.state().search_results.is_empty());
+ assert!(app.state().search_query.is_empty());
+ assert_eq!(app.state().input_mode, InputMode::Normal);
+
+ // Test /clear slash command
+ app.state_mut().search_results.push(SearchResult {
+ id: "2".to_string(),
+ title: "Inception".to_string(),
+ stype: 1,
+ release_year: "2010".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: ProviderKind::MovieBox,
+ });
+ app.state_mut().search_query.set_content("/clear");
+ app.handle_action(Action::Search {
+ query: "/clear".to_string(),
+ force_refresh: false,
+ })
+ .await;
+
+ assert!(app.state().search_results.is_empty());
+ assert!(app.state().search_query.is_empty());
+ assert_eq!(app.state().input_mode, InputMode::Normal);
+}
+
+#[tokio::test]
+async fn test_history_item_space_and_p_key_direct_resume() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Normal;
+ app.state_mut().search_query.set_content("/history");
+ app.state_mut().search_results.push(SearchResult {
+ id: "tv_100".to_string(),
+ title: "Breaking Bad".to_string(),
+ stype: 2,
+ release_year: "2008".to_string(),
+ cover_url: None,
+ season: 2,
+ episode: 4,
+ provider: ProviderKind::MovieBox,
+ });
+ app.state_mut().search_list_state.select(Some(0));
+ app.state_mut().last_search_edit =
+ std::time::Instant::now() - std::time::Duration::from_secs(1);
+
+ let space_key = KeyEvent::new(KeyCode::Char(' '), KeyModifiers::empty());
+ app.handle_action(Action::Key(space_key)).await;
+
+ assert_eq!(app.state().active_screen, Screen::Details);
+ assert_eq!(app.state().active_subject_id.as_deref(), Some("tv_100"));
+ assert_eq!(app.state().selected_season, 2);
+ assert_eq!(app.state().selected_episode, 4);
+ assert!(app.state().auto_play_on_ready);
+}
+
+#[tokio::test]
+async fn test_history_item_enter_pre_seeds_season_and_episode() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Normal;
+ app.state_mut().search_query.set_content("/history");
+ app.state_mut().search_results.push(SearchResult {
+ id: "tv_200".to_string(),
+ title: "Better Call Saul".to_string(),
+ stype: 2,
+ release_year: "2015".to_string(),
+ cover_url: None,
+ season: 3,
+ episode: 7,
+ provider: ProviderKind::MovieBox,
+ });
+ app.state_mut().search_list_state.select(Some(0));
+ app.state_mut().last_search_edit =
+ std::time::Instant::now() - std::time::Duration::from_secs(1);
+
+ app.handle_action(Action::Submit).await;
+
+ assert_eq!(app.state().active_screen, Screen::Details);
+ assert_eq!(app.state().active_subject_id.as_deref(), Some("tv_200"));
+ assert_eq!(app.state().selected_season, 3);
+ assert_eq!(app.state().selected_episode, 7);
+ assert!(!app.state().auto_play_on_ready);
+}
+
+#[tokio::test]
+async fn test_no_results_and_error_state_rendering_hints() {
+ let backend = TestBackend::new(100, 30);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let mut app = App::new();
+
+ // No results view
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Normal;
+ app.state_mut()
+ .search_query
+ .set_content("nonexistent_movie_xyz");
+ app.state_mut().search_results.clear();
+
+ terminal.draw(|frame| app.draw(frame)).unwrap();
+ let content = terminal.backend().buffer().content();
+ let text: String = content.iter().map(|c| c.symbol()).collect();
+ assert!(text.contains("Switch provider"));
+ assert!(text.contains("Browse categories"));
+ assert!(text.contains("Clear"));
+
+ // Error view
+ app.state_mut().search_error =
+ Some("Failed to connect to MovieBox provider: connection refused by server".to_string());
+ terminal.draw(|frame| app.draw(frame)).unwrap();
+ let content_err = terminal.backend().buffer().content();
+ let text_err: String = content_err.iter().map(|c| c.symbol()).collect();
+ assert!(text_err.contains("Retry request"));
+ assert!(text_err.contains("Switch provider"));
+ assert!(text_err.contains("Back"));
+}