Skip to content

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

feat(settings): unified interactive settings hub and streamlined slash commands

Samir Hossains78c14e09b521
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a4bc06..16b8891 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,7 @@
## [Unreleased]
### Added
+- **Unified Interactive Settings & Preferences Hub (`/settings`)**: Introduced a consolidated, mouse-friendly modal dialog replacing fragmented slash commands. Features 4 categorized tabs (`General`, `Content Modes`, `Appearance`, `Maintenance`), live player cycling (`Auto Detect`, `mpv`, `VLC`, `IINA`, `Android`), live theme cycling with palette preview swatches, inline download directory editing, and multi-mode toggling with safety guards. Streamlined slash command autocomplete suggestions while retaining full legacy command compatibility.
- **Stream list tabular column headers (`stream_table_header_spans`)**: Rendered aligned header row (`Quality`, `Size`, `Codecs`, `Duration`, `Release / Source`) at the top of stream results in the Details view on viewports $\ge 76$ columns.
- **Vim navigation in Theme picker (`j` / `k`)**: Added `j` (down) and `k` (up) key support to navigate and live-preview themes inside the `/theme` picker popup.
- **Live stream verification test suite (`tests/live_stream_verification.rs`)**: Integrated end-to-end verification verifying movie and series stream resolution against live backend endpoints and asserting absence of legacy notice hashes.
diff --git a/docs/config.md b/docs/config.md
index 048d618..507f2e6 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -19,6 +19,14 @@ macOS `~/Library/Application Support/moviebox-tui`, Linux `~/.config/moviebox-tu
| `default_player` | string or null | Preferred player: `mpv`, `iina`, `vlc`, `android`; absent/null until you choose one from the in-app picker. |
| `download_dir` | string or null | Custom directory for video and subtitle downloads (null uses OS default). |
+## Interactive Settings Hub (`/settings`)
+
+All settings in `config.json` can be configured interactively inside the application by typing `/settings` into the search bar.
+
+- **General**: Toggle automatic update checks, choose default media player (`mpv`, `VLC`, `IINA`, `Android`), and edit download folder path.
+- **Content Modes**: Enable or disable Streaming Mode, BDIX FTP sources, Live TV (IPTV), and HTTP Addons with safety guards (preventing 0 active modes).
+- **Appearance**: Cycle color themes live with real-time palette swatches or launch the visual theme swatch picker.
+- **Maintenance**: Purge disk cache, query GitHub for release updates, and view repository information.
## Other persisted files
- `addons_config.json` — list of installed HTTP addons in the config directory (see [addons-mode.md](addons-mode.md)).
diff --git a/docs/controls.md b/docs/controls.md
index d986f65..a94d051 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -67,11 +67,11 @@ All popup dialogs (Theme picker, Browse categories, Player picker, TV Manager, A
- **`*` / `f`**: Favorite / unfavorite the selected title on the Home screen.
- **`f`**: Favorite / unfavorite the open title on the Details screen.
- **`s`**: Open subtitle language picker on the Details screen.
+- **`/settings`**: Open interactive Settings & Preferences Hub.
- **`/browse`**: Open curated browse categories (Trending, Popular, Top Rated, etc.).
- **`/history`**: Open watch history (`Space` or `P` to instantly resume recorded episode/movie).
- **`/favorites`**: Open your starred titles.
- **`/clear`**: Clear active search query and return to landing.
-### TV Mode (Live IPTV)
- **`Enter`**: Play selected TV channel immediately.
- **`o`**: Open player selection picker for the channel.
- **`r`**: Reload all active M3U playlist sources.
@@ -111,22 +111,24 @@ Type these commands directly into the search bar:
| Command | Applicable Mode | Action |
| :--- | :--- | :--- |
+| `/settings` | All | Open interactive Settings & Preferences Hub |
| `/browse` | Streaming / Addon | Browse curated views (Trending, Popular) or Addon catalogs (Top Movies, Top Series) |
| `/history` | Streaming / Addon | View watch history with latest progress |
| `/favorites` | Streaming / Addon | View all starred titles |
+| `/theme` | All | Open visual theme swatch picker |
+| `/clear` | All | Clear search results and return to landing |
+| `/help` | All | Open interactive keybinding help menu |
| `/list` | TV | View live TV channels |
-| `/config` | TV / Addon | Manage IPTV playlists (TV Mode) or configure HTTP addons (Addon Mode) |
| `/download-dir` | All | View, change, or reset the download directory |
-| `/theme` | All | Open theme picker (Mocha, Latte, Macchiato, Frappe, Nord, TokyoNight, Dracula, Gruvbox, RosePine) |
-| `/clear-cache` | All | Clear temporary cache files |
| `/update` | All | Check if a new release is available on GitHub |
+| `/clear-cache` | All | Clear temporary cache files |
+| `/github` | All | Open the project repository |
| `/toggle-update` | All | Toggle automatic startup update checks |
-| `/toggle-streaming` | All | Toggle Streaming Mode navigation in bottom dock (aliases: `/enable-streaming`, `/disable-streaming`) |
-| `/toggle-tv` | All | Toggle TV Mode navigation in bottom dock (aliases: `/enable-tv`, `/disable-tv`) |
-| `/toggle-addons` | All | Toggle Addon Mode navigation in bottom dock (aliases: `/enable-addons`, `/disable-addons`) |
-| `/toggle-bdix` | Streaming | Toggle BDIX FTP sources (aliases: `/enable-bdix`, `/disable-bdix`) |
+| `/toggle-streaming` | All | Toggle Streaming Mode navigation in bottom dock |
+| `/toggle-tv` | All | Toggle TV Mode navigation in bottom dock |
+| `/toggle-addons` | All | Toggle Addon Mode navigation in bottom dock |
+| `/toggle-bdix` | Streaming | Toggle BDIX FTP sources |
| `/probe` | All | Re-run terminal graphics detection and report the result |
-| `/github` | All | Open the project repository |
## Help Overlay
diff --git a/src/tui/action.rs b/src/tui/action.rs
index 6bdae3b..57ea0d0 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -74,6 +74,13 @@ pub enum Action {
ShowDownloadSubtitlePopup(serde_json::Value),
ToggleThemePopup,
SelectTheme(String),
+ ToggleSettingsPopup,
+ ShowSettingsPopup,
+ CloseSettingsPopup,
+ SelectSettingsCategory(crate::tui::state::SettingsCategory),
+ SettingsAdjustValue(bool),
+ SettingsActivateRow,
+ SettingsResetDownloadDir,
ShowBrowseMenu,
SelectBrowse(crate::tui::state::BrowsePreset),
SelectAddonCatalog(crate::providers::addons::models::AddonCatalogTarget),
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 6217800..015dca2 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -215,6 +215,24 @@ impl App {
}
return None;
}
+ if self.state.player_picker_popup {
+ match key.code {
+ KeyCode::Esc => {
+ self.action_sender.send(Action::GoBack).ok();
+ }
+ KeyCode::Up | KeyCode::Char('k') => {
+ self.action_sender.send(Action::MoveUp).ok();
+ }
+ KeyCode::Down | KeyCode::Char('j') => {
+ self.action_sender.send(Action::MoveDown).ok();
+ }
+ KeyCode::Enter | KeyCode::Char(' ') => {
+ self.action_sender.send(Action::Submit).ok();
+ }
+ _ => {}
+ }
+ return None;
+ }
if self.state.show_theme_popup {
match key.code {
@@ -304,6 +322,99 @@ impl App {
}
return None;
}
+ if self.state.show_settings_popup {
+ if let Some(input) = &mut self.state.settings_download_dir_input {
+ match key.code {
+ KeyCode::Esc => {
+ self.state.settings_download_dir_input = None;
+ }
+ KeyCode::Enter => {
+ self.action_sender.send(Action::SettingsActivateRow).ok();
+ }
+ KeyCode::Left => {
+ input.move_left();
+ }
+ KeyCode::Right => {
+ input.move_right();
+ }
+ KeyCode::Home => {
+ input.move_home();
+ }
+ KeyCode::End => {
+ input.move_end();
+ }
+ KeyCode::Backspace => {
+ input.delete_backwards();
+ }
+ KeyCode::Delete => {
+ input.delete_forwards();
+ }
+ KeyCode::Char('u') | KeyCode::Char('U')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ input.clear();
+ }
+ KeyCode::Char('w') | KeyCode::Char('W')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ input.delete_word_backwards();
+ }
+ KeyCode::Char(c) if !c.is_control() => {
+ input.insert(c);
+ }
+ _ => {}
+ }
+ return None;
+ }
+
+ match key.code {
+ KeyCode::Esc => {
+ self.state.show_settings_popup = false;
+ self.state.settings_download_dir_input = None;
+ self.persist_config();
+ }
+ KeyCode::Tab => {
+ self.state.settings_next_category();
+ }
+ KeyCode::BackTab => {
+ self.state.settings_previous_category();
+ }
+ KeyCode::Up | KeyCode::Char('k') => {
+ self.state.settings_row_up();
+ }
+ KeyCode::Down | KeyCode::Char('j') => {
+ self.state.settings_row_down();
+ }
+ KeyCode::Left | KeyCode::Char('h') => {
+ self.action_sender
+ .send(Action::SettingsAdjustValue(false))
+ .ok();
+ }
+ KeyCode::Right | KeyCode::Char('l') => {
+ self.action_sender
+ .send(Action::SettingsAdjustValue(true))
+ .ok();
+ }
+ KeyCode::Char(' ') | KeyCode::Enter => {
+ self.action_sender.send(Action::SettingsActivateRow).ok();
+ }
+ KeyCode::Char('d') | KeyCode::Char('D')
+ if self.state.settings_category
+ == crate::tui::state::SettingsCategory::General
+ && self.state.settings_selected_row == 2 =>
+ {
+ self.action_sender
+ .send(Action::SettingsResetDownloadDir)
+ .ok();
+ }
+ _ => {}
+ }
+ return None;
+ }
if self.state.input_mode == InputMode::Normal
&& self.state.active_screen == Screen::Home
@@ -1239,17 +1350,7 @@ impl App {
}
fn has_active_modal(&self) -> bool {
- self.state.show_help
- || self.state.show_theme_popup
- || self.state.show_browse_popup
- || self.state.addon_manager_popup
- || self.state.tv_config_popup
- || self.state.update_available.is_some()
- || self.state.player_picker_popup
- || self.state.subtitle_popup
- || self.state.is_download_subtitle_popup
- || self.state.show_season_download_confirm
- || self.state.show_episode_download_confirm
+ self.state.has_active_modal()
}
}
@@ -1297,21 +1398,17 @@ mod tests {
];
app.state.search_list_state.select(Some(0));
- // Jump to End
app.handle_key(KeyEvent::new(KeyCode::End, KeyModifiers::empty()))
.await;
assert_eq!(app.state.search_list_state.selected(), Some(2));
- // Jump to Home
app.handle_key(KeyEvent::new(KeyCode::Home, KeyModifiers::empty()))
.await;
assert_eq!(app.state.search_list_state.selected(), Some(0));
- // Jump to End with G
app.handle_key(KeyEvent::new(KeyCode::Char('G'), KeyModifiers::SHIFT))
.await;
assert_eq!(app.state.search_list_state.selected(), Some(2));
- // Jump to Home with g
app.handle_key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::empty()))
.await;
assert_eq!(app.state.search_list_state.selected(), Some(0));
@@ -1347,11 +1444,9 @@ mod tests {
];
app.state.search_list_state.select(Some(0));
- // End key should fall through and jump to end of search list
app.handle_key(KeyEvent::new(KeyCode::End, KeyModifiers::empty()))
.await;
assert_eq!(app.state.search_list_state.selected(), Some(1));
- // Esc should dismiss the update modal
app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
.await;
assert!(app.state.update_available.is_none());
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 7820a4e..0cdf7c2 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -9,6 +9,8 @@ use ratatui::layout::{Constraint, Direction, Layout, Rect};
impl App {
pub(super) fn handle_mouse(&mut self, col: u16, row: u16) -> Option<Action> {
let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
+ let cols = if cols == 0 { 80 } else { cols };
+ let rows = if rows == 0 { 24 } else { rows };
let area = Rect::new(0, 0, cols, rows);
if self.handle_overlay_mouse(col, row, area) {
@@ -48,6 +50,38 @@ impl App {
return true;
}
}
+ if self.state.player_picker_popup {
+ let items = self
+ .state
+ .available_players
+ .iter()
+ .map(|k| k.label().to_string())
+ .collect::<Vec<_>>();
+ let confirm_label = if self.state.settings_player_picker {
+ "Select"
+ } else {
+ "Open"
+ };
+ match click_in_picker(
+ crate::tui::overlay::picker_layout(area, &items, confirm_label, 24),
+ col,
+ row,
+ &self.state.player_picker_state,
+ items.len(),
+ area,
+ ) {
+ Some(Some(clicked_idx)) => {
+ self.state.player_picker_state.select(Some(clicked_idx));
+ self.action_sender.send(Action::Submit).ok();
+ }
+ Some(None) => {}
+ None => {
+ self.state.player_picker_popup = false;
+ self.state.settings_player_picker = false;
+ }
+ }
+ return true;
+ }
if self.state.show_theme_popup {
let theme_names = crate::tui::theme::AVAILABLE_THEMES;
@@ -89,6 +123,40 @@ impl App {
}
return true;
}
+ if self.state.show_settings_popup {
+ let popup =
+ crate::tui::overlay::settings_modal_layout(area, self.state.settings_category);
+ if !popup.contains(ratatui::layout::Position::new(col, row)) {
+ self.state.show_settings_popup = false;
+ self.state.settings_download_dir_input = None;
+ self.persist_config();
+ return true;
+ }
+
+ if let Some(cat) = crate::tui::widgets::settings::settings_category_tab_at(
+ popup,
+ col,
+ row,
+ self.state.basic_terminal,
+ self.state.settings_category,
+ ) {
+ self.state.settings_select_category(cat);
+ return true;
+ }
+
+ if let Some(clicked_row) = crate::tui::widgets::settings::settings_row_at(
+ popup,
+ self.state.settings_category,
+ col,
+ row,
+ ) {
+ self.state.settings_selected_row = clicked_row;
+ self.action_sender.send(Action::SettingsActivateRow).ok();
+ return true;
+ }
+
+ return true;
+ }
if self.state.show_browse_popup {
let is_addon = self.state.mode() == crate::tui::state::AppMode::Addon;
@@ -186,33 +254,6 @@ impl App {
return true;
}
- if self.state.player_picker_popup {
- let items = self
- .state
- .available_players
- .iter()
- .map(|k| k.label().to_string())
- .collect::<Vec<_>>();
- match click_in_picker(
- crate::tui::overlay::picker_layout(area, &items, "Open", 24),
- col,
- row,
- &self.state.player_picker_state,
- items.len(),
- area,
- ) {
- Some(Some(clicked_idx)) => {
- self.state.player_picker_state.select(Some(clicked_idx));
- self.action_sender.send(Action::Submit).ok();
- }
- Some(None) => {}
- None => {
- self.state.player_picker_popup = false;
- }
- }
- return true;
- }
-
if self.state.subtitle_popup || self.state.is_download_subtitle_popup {
let items = self
.state
@@ -693,27 +734,36 @@ impl App {
Addon,
}
+ let current_mode = self.state.mode();
let mut buttons: Vec<(BottomBtn, u16)> = Vec::new();
- if self.state.streaming_enabled {
+ if self.state.streaming_enabled && current_mode != crate::tui::state::AppMode::Streaming {
let len = (3 + ctrl_s.len() + 6) as u16;
buttons.push((BottomBtn::Stream, len));
}
- if self.state.tv_enabled {
+ if self.state.tv_enabled && current_mode != crate::tui::state::AppMode::Tv {
let len = (3 + ctrl_t.len() + 2) as u16;
buttons.push((BottomBtn::Tv, len));
}
- if self.state.addons_enabled {
+ if self.state.addons_enabled && current_mode != crate::tui::state::AppMode::Addon {
let len = (3 + ctrl_a.len() + 5) as u16;
buttons.push((BottomBtn::Addon, len));
}
let mode_count = buttons.len();
let sep_len = if compact { 3 } else { 5 };
- let modes_total_w: u16 = buttons.iter().map(|(_, w)| *w).sum::<u16>()
- + (mode_count.saturating_sub(1) as u16) * sep_len;
+ let modes_total_w: u16 = if mode_count > 0 {
+ buttons.iter().map(|(_, w)| *w).sum::<u16>()
+ + (mode_count.saturating_sub(1) as u16) * sep_len
+ } else {
+ 0
+ };
- let util_gap = if compact { 4 } else { 7 };
+ let util_gap = if modes_total_w > 0 {
+ if compact { 4 } else { 7 }
+ } else {
+ 0
+ };
let help_w = if ultra_compact { 3 } else { 8 };
let quit_w = if ultra_compact { 3 } else { 8 };
let util_sep = 2;
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index d2862bb..4d06002 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -391,6 +391,7 @@ impl App {
self.state.player_picker_subtitle = None;
self.state.player_picker_playback = None;
self.state.player_picker_state.select(None);
+ self.state.settings_player_picker = false;
return None;
}
if self.state.subtitle_popup || self.state.is_download_subtitle_popup {
@@ -749,6 +750,7 @@ impl App {
}
self.state.player_picker_popup = false;
self.remember_player_preference(player);
+ self.state.settings_player_picker = false;
if let Some(source) = self.state.player_picker_playback.take() {
self.action_sender
.send(Action::LaunchPlayback(player, source))
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index bf689c6..fdbf8aa 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -46,6 +46,12 @@ impl App {
self.state.active_screen = Screen::Home;
self.state.available_players = crate::tui::player::detect();
+ if (self.state.default_player.is_none()
+ || self.state.default_player.as_deref() == Some("auto"))
+ && let Some(first) = self.state.available_players.first()
+ {
+ self.state.default_player = Some(first.config_key().to_string());
+ }
let preferred = std::env::var("MOVIEBOX_PLAYER")
.ok()
.and_then(|value| crate::tui::state::PlayerKind::parse(&value))
@@ -382,7 +388,14 @@ impl App {
| Action::UpdateAvailable(..)
| Action::StartSelfUpdate
| Action::SelfUpdateProgress(..)
- | Action::SelfUpdateComplete(..) => {
+ | Action::SelfUpdateComplete(..)
+ | Action::ToggleSettingsPopup
+ | Action::ShowSettingsPopup
+ | Action::CloseSettingsPopup
+ | Action::SelectSettingsCategory(..)
+ | Action::SettingsAdjustValue(..)
+ | Action::SettingsActivateRow
+ | Action::SettingsResetDownloadDir => {
self.handle_system(action).await;
}
@@ -523,7 +536,9 @@ impl App {
}
self.draw_download_gauge(frame, download_area);
+ self.draw_settings_modal(frame, area);
self.draw_theme_picker(frame, area);
+ self.draw_player_picker(frame, area);
self.draw_update_modal(frame, area);
crate::tui::overlay::notifications(
@@ -709,6 +724,39 @@ impl App {
);
}
}
+ fn draw_settings_modal(&mut self, frame: &mut Frame, area: Rect) {
+ if self.state.show_settings_popup {
+ crate::tui::widgets::settings::draw(frame, area, &mut self.state, &self.theme);
+ }
+ }
+ fn draw_player_picker(&mut self, frame: &mut Frame, area: Rect) {
+ if self.state.player_picker_popup {
+ let items = self
+ .state
+ .available_players
+ .iter()
+ .map(|k| k.label().to_string())
+ .collect::<Vec<_>>();
+ let (title, confirm_label) = if self.state.settings_player_picker {
+ ("Default Media Player", "Select")
+ } else {
+ ("Open with", "Open")
+ };
+ crate::tui::overlay::picker(
+ frame,
+ area,
+ &items,
+ &mut self.state.player_picker_state,
+ crate::tui::overlay::PickerSpec {
+ title,
+ confirm_label,
+ minimum_width: 24,
+ },
+ &self.theme,
+ self.state.basic_terminal,
+ );
+ }
+ }
fn draw_update_modal(&self, frame: &mut Frame, area: Rect) {
if let Some((version, notes)) = &self.state.update_available {
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index eeee0c6..b73b43d 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -126,6 +126,12 @@ impl App {
let ctrl_a = crate::tui::text::ctrl_key("A");
match parsed {
+ crate::tui::commands::ParsedCommand::Settings => {
+ self.state.search_query.clear();
+ self.state.input_mode = InputMode::Normal;
+ self.action_sender.send(Action::ToggleSettingsPopup).ok();
+ Some(true)
+ }
crate::tui::commands::ParsedCommand::ClearCache => {
self.state.search_query.clear();
self.state.input_mode = InputMode::Normal;
@@ -138,6 +144,12 @@ impl App {
self.state.set_status_default("Search cleared.");
Some(true)
}
+ crate::tui::commands::ParsedCommand::Help => {
+ self.state.search_query.clear();
+ self.state.input_mode = InputMode::Normal;
+ self.action_sender.send(Action::ToggleHelp).ok();
+ Some(true)
+ }
crate::tui::commands::ParsedCommand::Github => {
let _ = open::that("https://github.com/mesamirh/MovieBox-Tui");
self.state.search_query.clear();
@@ -250,15 +262,9 @@ impl App {
} else if current_mode == crate::tui::state::AppMode::Addon {
self.action_sender.send(Action::ShowAddonManager).ok();
} else {
- let ctrl_t = crate::tui::text::ctrl_key("T");
- let ctrl_a = crate::tui::text::ctrl_key("A");
self.state.search_query.clear();
self.state.input_mode = InputMode::Normal;
- self.state.notify(
- NotificationKind::Info,
- "Configuration",
- format!("Command /config is available in TV Mode ({ctrl_t}) or Addon Mode ({ctrl_a})."),
- );
+ self.action_sender.send(Action::ToggleSettingsPopup).ok();
}
Some(true)
}
@@ -306,20 +312,8 @@ impl App {
);
return Some(true);
}
- let expanded_path = if let Some(stripped) = clean_arg
- .strip_prefix("~/")
- .or_else(|| clean_arg.strip_prefix("~\\"))
- {
- if let Some(home) = dirs::home_dir() {
- home.join(stripped)
- } else {
- std::path::PathBuf::from(clean_arg)
- }
- } else if clean_arg == "~" {
- dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from(clean_arg))
- } else {
- std::path::PathBuf::from(clean_arg)
- };
+ let expanded_path = crate::tui::state::AppState::expand_download_path(clean_arg)
+ .unwrap_or_else(|| std::path::PathBuf::from(clean_arg));
match std::fs::create_dir_all(&expanded_path) {
Ok(_) => {
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 477cc4f..609113d 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -283,6 +283,340 @@ impl App {
.notify(NotificationKind::Error, "Cache Clear Failed", error);
}
},
+ Action::ToggleSettingsPopup => {
+ let open = !self.state.show_settings_popup;
+ if open {
+ self.reset_transient_overlays();
+ self.state.ensure_default_player();
+ self.state.show_settings_popup = true;
+ self.state.settings_category = crate::tui::state::SettingsCategory::General;
+ self.state.settings_selected_row = 0;
+ self.state.settings_download_dir_input = None;
+ self.state.settings_player_picker = false;
+ self.state.input_mode = crate::tui::state::InputMode::Normal;
+ } else {
+ self.state.show_settings_popup = false;
+ self.state.settings_download_dir_input = None;
+ self.state.settings_player_picker = false;
+ self.persist_config();
+ }
+ }
+
+ Action::ShowSettingsPopup => {
+ self.reset_transient_overlays();
+ self.state.ensure_default_player();
+ self.state.show_settings_popup = true;
+ self.state.settings_category = crate::tui::state::SettingsCategory::General;
+ self.state.settings_selected_row = 0;
+ self.state.settings_download_dir_input = None;
+ self.state.settings_player_picker = false;
+ self.state.input_mode = crate::tui::state::InputMode::Normal;
+ }
+
+ Action::CloseSettingsPopup => {
+ self.state.show_settings_popup = false;
+ self.state.settings_download_dir_input = None;
+ self.state.settings_player_picker = false;
+ self.persist_config();
+ }
+
+ Action::SelectSettingsCategory(cat) => {
+ self.state.settings_select_category(cat);
+ }
+
+ Action::SettingsResetDownloadDir => {
+ self.state.download_dir = None;
+ self.state.settings_download_dir_input = None;
+ self.persist_config();
+ let default_dir = crate::logging::sanitize_path(self.resolve_download_base_dir());
+ self.state.notify(
+ NotificationKind::Success,
+ "Download Folder",
+ format!("Reset download folder to default ({default_dir})"),
+ );
+ }
+
+ Action::SettingsAdjustValue(forward) => match self.state.settings_category {
+ crate::tui::state::SettingsCategory::General => {
+ match self.state.settings_selected_row {
+ 0 => {
+ self.state.auto_update = !self.state.auto_update;
+ self.persist_config();
+ }
+ 1 => {
+ self.state.cycle_settings_player(forward);
+ self.persist_config();
+ }
+ _ => {}
+ }
+ }
+ crate::tui::state::SettingsCategory::ContentModes => {
+ match self.state.settings_selected_row {
+ 0 => {
+ let enable_req = !self.state.streaming_enabled;
+ if !enable_req && !self.state.can_disable_streaming_mode() {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Streaming Mode",
+ "Cannot disable: at least one mode must remain active.",
+ );
+ } else {
+ self.state.streaming_enabled = enable_req;
+ self.persist_config();
+ if !self.state.streaming_enabled
+ && !self.state.is_tv_mode
+ && !self.state.is_addon_mode
+ {
+ if self.state.tv_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Tv);
+ } else if self.state.addons_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Addon);
+ }
+ }
+ }
+ }
+ 1 => {
+ self.state.bdix_enabled = !self.state.bdix_enabled;
+ self.persist_config();
+ }
+ 2 => {
+ let enable_req = !self.state.tv_enabled;
+ if !enable_req && !self.state.can_disable_tv_mode() {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Live TV Mode",
+ "Cannot disable: at least one mode must remain active.",
+ );
+ } else {
+ self.state.tv_enabled = enable_req;
+ self.persist_config();
+ if !self.state.tv_enabled && self.state.is_tv_mode {
+ if self.state.streaming_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Streaming);
+ } else if self.state.addons_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Addon);
+ }
+ }
+ }
+ }
+ 3 => {
+ let enable_req = !self.state.addons_enabled;
+ if !enable_req && !self.state.can_disable_addons_mode() {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Addon Mode",
+ "Cannot disable: at least one mode must remain active.",
+ );
+ } else {
+ self.state.addons_enabled = enable_req;
+ self.persist_config();
+ if !self.state.addons_enabled && self.state.is_addon_mode {
+ if self.state.streaming_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Streaming);
+ } else if self.state.tv_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Tv);
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ crate::tui::state::SettingsCategory::Appearance => {
+ if self.state.settings_selected_row == 0 {
+ let next_theme = self.state.cycle_settings_theme(forward);
+ let kind = crate::tui::theme::ThemeKind::parse(&next_theme);
+ self.theme = crate::tui::theme::Theme::from_kind(kind);
+ self.persist_config();
+ self.state.dirty = true;
+ }
+ }
+ crate::tui::state::SettingsCategory::StorageInfo => {}
+ },
+
+ Action::SettingsActivateRow => match self.state.settings_category {
+ crate::tui::state::SettingsCategory::General => {
+ match self.state.settings_selected_row {
+ 0 => {
+ self.state.auto_update = !self.state.auto_update;
+ self.persist_config();
+ }
+ 1 => {
+ if !self.state.available_players.is_empty() {
+ self.state.settings_player_picker = true;
+ self.state.player_picker_popup = true;
+ self.state.player_picker_playback = None;
+ self.state.player_picker_link = None;
+ self.state.player_picker_subtitle = None;
+ let selected_idx =
+ self.state
+ .default_player
+ .as_deref()
+ .and_then(|k| {
+ self.state.available_players.iter().position(|p| {
+ p.config_key().eq_ignore_ascii_case(k)
+ })
+ })
+ .unwrap_or(0);
+ self.state.player_picker_state.select(Some(selected_idx));
+ }
+ }
+ 2 => {
+ if let Some(input) = self.state.settings_download_dir_input.take() {
+ let new_path = input.as_str().trim();
+ if let Some(pb) =
+ crate::tui::state::AppState::expand_download_path(new_path)
+ {
+ self.state.download_dir = Some(pb.clone());
+ self.persist_config();
+ self.state.notify(
+ NotificationKind::Success,
+ "Download Folder",
+ format!("Download folder set to {}", pb.display()),
+ );
+ } else {
+ self.state.download_dir = None;
+ self.persist_config();
+ let default_dir = crate::logging::sanitize_path(
+ self.resolve_download_base_dir(),
+ );
+ self.state.notify(
+ NotificationKind::Success,
+ "Download Folder",
+ format!("Reset download folder to default ({default_dir})"),
+ );
+ }
+ } else {
+ let current = self
+ .state
+ .download_dir
+ .as_ref()
+ .map(|p| p.to_string_lossy().to_string())
+ .unwrap_or_default();
+ self.state.settings_download_dir_input =
+ Some(crate::tui::text::TextInputBuffer::from_str(&current));
+ }
+ }
+ _ => {}
+ }
+ }
+ crate::tui::state::SettingsCategory::ContentModes => {
+ match self.state.settings_selected_row {
+ 0 => {
+ let enable_req = !self.state.streaming_enabled;
+ if !enable_req && !self.state.can_disable_streaming_mode() {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Streaming Mode",
+ "Cannot disable: at least one mode must remain active.",
+ );
+ } else {
+ self.state.streaming_enabled = enable_req;
+ self.persist_config();
+ if !self.state.streaming_enabled
+ && !self.state.is_tv_mode
+ && !self.state.is_addon_mode
+ {
+ if self.state.tv_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Tv);
+ } else if self.state.addons_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Addon);
+ }
+ }
+ }
+ }
+ 1 => {
+ self.state.bdix_enabled = !self.state.bdix_enabled;
+ self.persist_config();
+ }
+ 2 => {
+ let enable_req = !self.state.tv_enabled;
+ if !enable_req && !self.state.can_disable_tv_mode() {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Live TV Mode",
+ "Cannot disable: at least one mode must remain active.",
+ );
+ } else {
+ self.state.tv_enabled = enable_req;
+ self.persist_config();
+ if !self.state.tv_enabled && self.state.is_tv_mode {
+ if self.state.streaming_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Streaming);
+ } else if self.state.addons_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Addon);
+ }
+ }
+ }
+ }
+ 3 => {
+ let enable_req = !self.state.addons_enabled;
+ if !enable_req && !self.state.can_disable_addons_mode() {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Addon Mode",
+ "Cannot disable: at least one mode must remain active.",
+ );
+ } else {
+ self.state.addons_enabled = enable_req;
+ self.persist_config();
+ if !self.state.addons_enabled && self.state.is_addon_mode {
+ if self.state.streaming_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Streaming);
+ } else if self.state.tv_enabled {
+ self.state.set_mode(crate::tui::state::AppMode::Tv);
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ crate::tui::state::SettingsCategory::Appearance => {
+ if self.state.settings_selected_row == 0 {
+ self.state.original_theme_kind = Some(self.state.active_theme_kind.clone());
+ self.state.show_theme_popup = true;
+ if let Some(idx) = crate::tui::theme::AVAILABLE_THEMES
+ .iter()
+ .position(|&t| t.eq_ignore_ascii_case(&self.state.active_theme_kind))
+ {
+ self.state.theme_list_state.select(Some(idx));
+ } else {
+ self.state.theme_list_state.select(Some(0));
+ }
+ }
+ }
+ crate::tui::state::SettingsCategory::StorageInfo => {
+ match self.state.settings_selected_row {
+ 0 => {
+ self.state.notify(
+ NotificationKind::Info,
+ "Clearing Cache",
+ "Clearing temporary disk cache files...",
+ );
+ self.action_sender.send(Action::ClearCache).ok();
+ }
+ 1 => {
+ self.state.manual_update_check = true;
+ self.state.notify(
+ NotificationKind::Info,
+ "Checking for updates",
+ "Querying GitHub for latest releases...",
+ );
+ self.action_sender.send(Action::CheckForUpdates).ok();
+ }
+ 2 => {
+ let _ = open::that("https://github.com/mesamirh/MovieBox-Tui");
+ self.state.notify(
+ NotificationKind::Info,
+ "GitHub",
+ "Opening repository in default web browser...",
+ );
+ }
+ _ => {}
+ }
+ }
+ },
Action::ToggleThemePopup => {
let open = !self.state.show_theme_popup;
diff --git a/src/tui/app/tv.rs b/src/tui/app/tv.rs
index ea09e33..6febd52 100644
--- a/src/tui/app/tv.rs
+++ b/src/tui/app/tv.rs
@@ -6,10 +6,14 @@ impl App {
self.state.show_help = false;
self.state.show_theme_popup = false;
self.state.show_browse_popup = false;
+ self.state.show_settings_popup = false;
+ self.state.settings_download_dir_input = None;
self.state.player_picker_popup = false;
self.state.player_picker_link = None;
self.state.player_picker_subtitle = None;
self.state.player_picker_playback = None;
+ self.state.settings_player_picker = false;
+
self.state.subtitle_popup = false;
self.state.is_download_subtitle_popup = false;
self.state.pending_play_link = None;
diff --git a/src/tui/commands.rs b/src/tui/commands.rs
index b048145..186ceb0 100644
--- a/src/tui/commands.rs
+++ b/src/tui/commands.rs
@@ -2,18 +2,20 @@ use crate::tui::state::AppState;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlashCommand {
+ Settings,
Browse,
History,
Favorites,
+ Theme,
+ Clear,
+ Help,
List,
Config,
DownloadDir,
- Theme,
Update,
- ToggleUpdate,
ClearCache,
- Clear,
Github,
+ ToggleUpdate,
ToggleBdix,
ToggleStreaming,
ToggleTv,
@@ -23,18 +25,20 @@ pub enum SlashCommand {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsedCommand<'a> {
+ Settings,
Browse,
History,
Favorites,
+ Theme,
+ Clear,
+ Help,
List,
Config,
DownloadDir(&'a str),
- Theme,
Update,
- ToggleUpdate,
ClearCache,
- Clear,
Github,
+ ToggleUpdate,
ToggleBdix,
ToggleStreaming,
ToggleTv,
@@ -43,40 +47,56 @@ pub enum ParsedCommand<'a> {
}
impl SlashCommand {
- pub const ALL: [Self; 17] = [
+ pub const ALL: [Self; 13] = [
+ Self::Settings,
Self::Browse,
Self::History,
Self::Favorites,
+ Self::Theme,
+ Self::Clear,
+ Self::Help,
Self::List,
Self::Config,
Self::DownloadDir,
- Self::Theme,
Self::Update,
- Self::ToggleUpdate,
Self::ClearCache,
- Self::Clear,
Self::Github,
+ ];
+
+ pub const PRIMARY: [Self; 7] = [
+ Self::Settings,
+ Self::Browse,
+ Self::History,
+ Self::Favorites,
+ Self::Theme,
+ Self::Clear,
+ Self::Help,
+ ];
+
+ pub const TOGGLE_COMMANDS: [Self; 5] = [
+ Self::ToggleUpdate,
Self::ToggleBdix,
Self::ToggleStreaming,
Self::ToggleTv,
Self::ToggleAddons,
- Self::Probe,
];
pub fn name(self) -> &'static str {
match self {
+ Self::Settings => "/settings",
Self::Browse => "/browse",
Self::History => "/history",
Self::Favorites => "/favorites",
+ Self::Theme => "/theme",
+ Self::Clear => "/clear",
+ Self::Help => "/help",
Self::List => "/list",
Self::Config => "/config",
Self::DownloadDir => "/download-dir",
- Self::Theme => "/theme",
Self::Update => "/update",
- Self::ToggleUpdate => "/toggle-update",
Self::ClearCache => "/clear-cache",
- Self::Clear => "/clear",
Self::Github => "/github",
+ Self::ToggleUpdate => "/toggle-update",
Self::ToggleBdix => "/toggle-bdix",
Self::ToggleStreaming => "/toggle-streaming",
Self::ToggleTv => "/toggle-tv",
@@ -87,24 +107,28 @@ impl SlashCommand {
pub fn description(self, state: &AppState) -> &'static str {
match self {
+ Self::Settings => "Interactive preferences, content modes & configuration",
Self::Browse => "Curated, rated & most-watched views",
Self::History => "Watch history",
Self::Favorites => "Starred titles",
+ Self::Theme => "Theme picker",
+ Self::Clear => "Clear search results and return to landing",
+ Self::Help => "Open interactive keybinding help menu",
Self::List => "Show all TV channels",
Self::Config => {
if state.is_addon_mode {
"Configure HTTP addons"
- } else {
+ } else if state.is_tv_mode {
"Configure IPTV playlists"
+ } else {
+ "Interactive preferences and configuration"
}
}
Self::DownloadDir => "View or change download folder",
- Self::Theme => "Theme picker",
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::ToggleUpdate => "Toggle automatic update checks",
Self::ToggleBdix => "Toggle BDIX FTP sources",
Self::ToggleStreaming => "Toggle Streaming mode navigation",
Self::ToggleTv => "Toggle TV mode navigation",
@@ -115,6 +139,7 @@ impl SlashCommand {
pub fn is_available(self, state: &AppState) -> bool {
match self {
+ Self::Settings => true,
Self::Browse => {
(state.streaming_enabled && !state.is_tv_mode && !state.is_addon_mode)
|| (state.addons_enabled && state.is_addon_mode)
@@ -125,21 +150,19 @@ impl SlashCommand {
}
Self::Favorites => state.favorites_available(),
Self::List => state.tv_enabled && state.is_tv_mode,
- Self::Config => {
- (state.tv_enabled && state.is_tv_mode)
- || (state.addons_enabled && state.is_addon_mode)
- }
+ Self::Config => true,
Self::ToggleBdix => !state.is_tv_mode && !state.is_addon_mode,
- Self::ToggleStreaming
- | Self::ToggleTv
- | Self::ToggleAddons
+ Self::Theme
+ | Self::Clear
+ | Self::Help
| Self::DownloadDir
- | Self::Theme
| Self::Update
- | Self::ToggleUpdate
| Self::ClearCache
- | Self::Clear
| Self::Github
+ | Self::ToggleUpdate
+ | Self::ToggleStreaming
+ | Self::ToggleTv
+ | Self::ToggleAddons
| Self::Probe => true,
}
}
@@ -148,24 +171,35 @@ impl SlashCommand {
let lower = query.to_ascii_lowercase();
let mut results = Vec::new();
- for cmd in Self::ALL {
+ if lower.starts_with("/toggle-") {
+ for cmd in Self::TOGGLE_COMMANDS {
+ if !cmd.is_available(state) {
+ continue;
+ }
+ let name = cmd.name();
+ if name.starts_with(&lower) {
+ results.push(name.to_string());
+ }
+ }
+ return results;
+ }
+
+ let primary_suggestions: [(&str, Self); 7] = [
+ ("/settings", Self::Settings),
+ ("/browse", Self::Browse),
+ ("/history", Self::History),
+ ("/favorites", Self::Favorites),
+ ("/theme", Self::Theme),
+ ("/clear", Self::Clear),
+ ("/help", Self::Help),
+ ];
+
+ for (name, cmd) in primary_suggestions {
if !cmd.is_available(state) {
continue;
}
- let name = cmd.name();
if name.starts_with(&lower) {
results.push(name.to_string());
- if cmd == Self::DownloadDir
- && state.download_dir.is_some()
- && "/download-dir reset".starts_with(&lower)
- {
- results.push("/download-dir reset".to_string());
- }
- } else if cmd == Self::DownloadDir
- && state.download_dir.is_some()
- && "/download-dir reset".starts_with(&lower)
- {
- results.push("/download-dir reset".to_string());
}
}
@@ -182,13 +216,35 @@ impl SlashCommand {
if trimmed == "/download-dir reset" {
return Some("Reset download folder to default");
}
+ if trimmed == "/pref" || trimmed == "/preferences" || trimmed == "/options" {
+ return Some("Interactive preferences, content modes & configuration");
+ }
+ if trimmed == "/?" {
+ return Some("Open interactive keybinding help menu");
+ }
- for cmd in Self::ALL {
- if cmd.name() == trimmed {
- return Some(cmd.description(state));
- }
+ match trimmed {
+ "/settings" => Some(Self::Settings.description(state)),
+ "/browse" => Some(Self::Browse.description(state)),
+ "/history" => Some(Self::History.description(state)),
+ "/favorites" => Some(Self::Favorites.description(state)),
+ "/theme" => Some(Self::Theme.description(state)),
+ "/clear" => Some(Self::Clear.description(state)),
+ "/help" => Some(Self::Help.description(state)),
+ "/list" => Some(Self::List.description(state)),
+ "/config" => Some(Self::Config.description(state)),
+ "/download-dir" => Some(Self::DownloadDir.description(state)),
+ "/update" => Some(Self::Update.description(state)),
+ "/clear-cache" => Some(Self::ClearCache.description(state)),
+ "/github" => Some(Self::Github.description(state)),
+ "/toggle-update" => Some(Self::ToggleUpdate.description(state)),
+ "/toggle-bdix" => Some(Self::ToggleBdix.description(state)),
+ "/toggle-streaming" => Some(Self::ToggleStreaming.description(state)),
+ "/toggle-tv" => Some(Self::ToggleTv.description(state)),
+ "/toggle-addons" => Some(Self::ToggleAddons.description(state)),
+ "/probe" => Some(Self::Probe.description(state)),
+ _ => None,
}
- None
}
pub fn parse(input: &str) -> Option<ParsedCommand<'_>> {
@@ -202,18 +258,20 @@ impl SlashCommand {
let arg = parts.next().unwrap_or("").trim();
match command_name.to_ascii_lowercase().as_str() {
+ "/settings" | "/pref" | "/preferences" | "/options" => Some(ParsedCommand::Settings),
"/browse" => Some(ParsedCommand::Browse),
"/history" => Some(ParsedCommand::History),
"/favorites" => Some(ParsedCommand::Favorites),
+ "/theme" => Some(ParsedCommand::Theme),
+ "/clear" => Some(ParsedCommand::Clear),
+ "/help" | "/?" => Some(ParsedCommand::Help),
"/list" => Some(ParsedCommand::List),
"/config" => Some(ParsedCommand::Config),
"/download-dir" => Some(ParsedCommand::DownloadDir(arg)),
- "/theme" => Some(ParsedCommand::Theme),
"/update" => Some(ParsedCommand::Update),
- "/toggle-update" => Some(ParsedCommand::ToggleUpdate),
"/clear-cache" => Some(ParsedCommand::ClearCache),
- "/clear" => Some(ParsedCommand::Clear),
"/github" => Some(ParsedCommand::Github),
+ "/toggle-update" => Some(ParsedCommand::ToggleUpdate),
"/toggle-bdix" | "/enable-bdix" | "/disable-bdix" => Some(ParsedCommand::ToggleBdix),
"/toggle-streaming" | "/enable-streaming" | "/disable-streaming" => {
Some(ParsedCommand::ToggleStreaming)
@@ -231,71 +289,35 @@ impl SlashCommand {
#[cfg(test)]
mod tests {
use super::*;
- use std::path::PathBuf;
-
#[test]
- fn test_download_dir_suggest_default_state() {
+ fn test_primary_commands_suggest() {
let state = AppState::default();
- assert!(state.download_dir.is_none());
-
- let suggestions = SlashCommand::suggest(&state, "/download-dir");
- assert!(suggestions.contains(&"/download-dir".to_string()));
- assert!(!suggestions.contains(&"/download-dir reset".to_string()));
- }
-
- #[test]
- fn test_download_dir_suggest_custom_state() {
- let state = AppState {
- download_dir: Some(PathBuf::from("/custom/downloads")),
- ..Default::default()
- };
-
- let suggestions = SlashCommand::suggest(&state, "/download-dir");
- assert!(suggestions.contains(&"/download-dir".to_string()));
- assert!(suggestions.contains(&"/download-dir reset".to_string()));
-
- let d_suggestions = SlashCommand::suggest(&state, "/d");
- assert!(d_suggestions.contains(&"/download-dir".to_string()));
- assert!(d_suggestions.contains(&"/download-dir reset".to_string()));
- }
-
- #[test]
- fn test_download_dir_suggest_subcommand_prefix() {
- let state = AppState {
- download_dir: Some(PathBuf::from("/custom/downloads")),
- ..Default::default()
- };
-
- let suggestions = SlashCommand::suggest(&state, "/download-dir r");
- assert_eq!(suggestions, vec!["/download-dir reset".to_string()]);
-
- let suggestions_space = SlashCommand::suggest(&state, "/download-dir ");
- assert_eq!(suggestions_space, vec!["/download-dir reset".to_string()]);
- }
+ let suggestions = SlashCommand::suggest(&state, "/");
+ assert_eq!(
+ suggestions,
+ vec![
+ "/settings".to_string(),
+ "/browse".to_string(),
+ "/history".to_string(),
+ "/favorites".to_string(),
+ "/theme".to_string(),
+ "/clear".to_string(),
+ "/help".to_string(),
+ ]
+ );
- #[test]
- fn test_download_dir_suggest_mode_parity() {
- let mut state = AppState {
- download_dir: Some(PathBuf::from("/custom/downloads")),
- ..Default::default()
- };
+ let s_sug = SlashCommand::suggest(&state, "/s");
+ assert_eq!(s_sug, vec!["/settings".to_string()]);
- state.is_addon_mode = false;
- state.is_tv_mode = false;
- let stream_sug = SlashCommand::suggest(&state, "/download-dir");
- assert!(stream_sug.contains(&"/download-dir reset".to_string()));
+ let c_sug = SlashCommand::suggest(&state, "/c");
+ assert_eq!(c_sug, vec!["/clear".to_string()]);
- state.is_addon_mode = true;
- state.is_tv_mode = false;
- let addon_sug = SlashCommand::suggest(&state, "/download-dir");
- assert!(addon_sug.contains(&"/download-dir reset".to_string()));
+ let p_sug = SlashCommand::suggest(&state, "/p");
+ assert!(p_sug.is_empty());
- state.is_addon_mode = false;
- state.is_tv_mode = true;
- let tv_sug = SlashCommand::suggest(&state, "/download-dir");
- assert!(tv_sug.contains(&"/download-dir reset".to_string()));
+ let d_sug = SlashCommand::suggest(&state, "/download-dir");
+ assert!(d_sug.is_empty());
}
-
#[test]
fn test_favorites_command_parses_and_is_available_by_default() {
let state = AppState::default();
@@ -319,10 +341,15 @@ mod tests {
#[test]
fn test_toggle_commands_and_aliases_parse() {
let state = AppState::default();
- assert_eq!(SlashCommand::ALL.len(), 17);
+ assert_eq!(SlashCommand::ALL.len(), 13);
assert_eq!(SlashCommand::parse("/clear"), Some(ParsedCommand::Clear));
assert!(SlashCommand::Clear.is_available(&state));
assert_eq!(SlashCommand::Clear.name(), "/clear");
+ assert_eq!(SlashCommand::parse("/help"), Some(ParsedCommand::Help));
+ assert_eq!(SlashCommand::parse("/?"), Some(ParsedCommand::Help));
+ assert!(SlashCommand::Help.is_available(&state));
+ assert_eq!(SlashCommand::Help.name(), "/help");
+
assert_eq!(
SlashCommand::parse("/toggle-tv"),
Some(ParsedCommand::ToggleTv)
@@ -349,12 +376,15 @@ mod tests {
Some(ParsedCommand::ToggleAddons)
);
+ let toggle_no_dash = SlashCommand::suggest(&state, "/toggle");
+ assert!(toggle_no_dash.is_empty());
+
let toggle_sug = SlashCommand::suggest(&state, "/toggle-");
- assert!(toggle_sug.contains(&"/toggle-tv".to_string()));
- assert!(toggle_sug.contains(&"/toggle-addons".to_string()));
+ assert!(toggle_sug.contains(&"/toggle-update".to_string()));
assert!(toggle_sug.contains(&"/toggle-bdix".to_string()));
- assert!(toggle_sug.contains(&"/toggle-streaming".to_string()));
- assert!(!toggle_sug.contains(&"/enable-tv".to_string()));
+
+ let probe_sug = SlashCommand::suggest(&state, "/probe");
+ assert!(probe_sug.is_empty());
}
#[test]
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index e7e9d01..446333f 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -79,6 +79,13 @@ pub fn addon_manager_layout(area: Rect, addons_count: usize, input_active: bool)
};
centered(area, popup_width, popup_height, 36, 80)
}
+pub fn settings_modal_layout(area: Rect, category: crate::tui::state::SettingsCategory) -> Rect {
+ let popup_width = 76u16.min(area.width.saturating_sub(4)).max(52);
+ let content_height = (category.row_count() as u16 * 2).max(4);
+ let desired_height = 2 + 1 + content_height + 2 + 2;
+ let popup_height = desired_height.min(area.height.saturating_sub(2)).max(11);
+ centered(area, popup_width, popup_height, 52, 76)
+}
pub fn download_confirm_layout(
area: Rect,
@@ -431,7 +438,11 @@ pub fn border_type(basic_terminal: bool) -> BorderType {
}
pub(crate) fn key_hint(key: &str, action: &str, theme: &Theme) -> Span<'static> {
- Span::styled(format!("[{key}] {action}"), theme.text_dim)
+ if action.is_empty() {
+ Span::styled(format!("[{key}]"), theme.text_dim)
+ } else {
+ Span::styled(format!("[{key}] {action}"), theme.text_dim)
+ }
}
pub(crate) fn selection_style(theme: &Theme, basic_terminal: bool) -> Style {
@@ -718,8 +729,6 @@ mod tests {
let summary_lines = 3;
let action_row = download_confirm_action_row(popup, summary_lines);
- // Borders = 1 (top border at popup.y), Summary = 3 lines (popup.y + 1 .. popup.y + 4)
- // Action row = popup.y + 1 + 3 = popup.y + 4
assert_eq!(action_row, popup.y + 4);
assert!(popup.contains(ratatui::layout::Position::new(popup.x + 2, action_row)));
}
@@ -733,7 +742,7 @@ mod tests {
let action_row = download_confirm_action_row(popup, summary_lines);
assert!(popup.contains(ratatui::layout::Position::new(popup.x + 1, action_row)));
- assert!(action_row < popup.bottom() - 1); // Action row is inside inner area before footer/border
+ assert!(action_row < popup.bottom() - 1);
}
#[test]
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index 6e24a8f..e6ae3fc 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -1056,17 +1056,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let is_wide = streams_area.width > 110;
let stream_width = streams_area.width.saturating_sub(6) as usize;
- // 1. Pointer (2 chars)
let mut stream_spans = vec![Span::styled(pointer, marker_style)];
- // 2. Resolution Badge (7 chars + 1 space separator = 8 chars)
stream_spans.extend(resolution_badge_spans(
resolution,
theme,
state.basic_terminal,
));
- // 3. File Size (format!("{:>7} ") = 9 chars)
stream_spans.push(Span::styled(
format!("{size_formatted:>7} "),
primary_style,
@@ -1102,14 +1099,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
};
if is_compact {
- // 4. Codec (format!("{:<5} ") = 6 chars)
let codec_display = crate::tui::text::truncate_width(&codec_str, 5);
stream_spans.push(Span::styled(
format!("{codec_display:<5} "),
secondary_style,
));
- // 5. Title (Flex Min 20)
let used_prefix = stream_spans
.iter()
.map(|s| crate::tui::text::width(s.content.as_ref()))
@@ -1121,14 +1116,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
stream_spans.push(Span::styled(title_trunc, primary_style));
}
} else if is_wide {
- // 4. Extended Tags (format!("{:<22} ") = 23 chars)
let tags_display = crate::tui::text::truncate_width(&tags_or_codec, 22);
stream_spans.push(Span::styled(
format!("{tags_display:<22} "),
secondary_style,
));
- // 5. Duration (format!("{:<8} ") = 9 chars)
let duration_display =
crate::tui::text::truncate_width(&duration_col, 8);
stream_spans.push(Span::styled(
@@ -1136,7 +1129,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
secondary_style,
));
- // 6. Uploader (format!("{:<14} ") = 16 chars)
let uploader_display =
if upload_by != "Unknown" && !upload_by.is_empty() {
format!(
@@ -1148,7 +1140,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
};
stream_spans.push(Span::styled(uploader_display, secondary_style));
- // 7. Title (Flex)
let used_prefix = stream_spans
.iter()
.map(|s| crate::tui::text::width(s.content.as_ref()))
@@ -1160,15 +1151,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
stream_spans.push(Span::styled(title_trunc, primary_style));
}
} else {
- // Standard (76..=110 cols)
- // 4. Media Tags (format!("{:<14} ") = 15 chars)
let tags_display = crate::tui::text::truncate_width(&tags_or_codec, 14);
stream_spans.push(Span::styled(
format!("{tags_display:<14} "),
secondary_style,
));
- // 5. Duration (format!("{:<8} ") = 9 chars)
let duration_display =
crate::tui::text::truncate_width(&duration_col, 8);
stream_spans.push(Span::styled(
@@ -1176,7 +1164,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
secondary_style,
));
- // 6. Uploader / Release Title (cleanly truncated to remaining width)
let used_prefix_width = stream_spans
.iter()
.map(|s| crate::tui::text::width(s.content.as_ref()))
@@ -1471,27 +1458,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
);
}
- if state.player_picker_popup {
- let items = state
- .available_players
- .iter()
- .map(|k| k.label().to_string())
- .collect::<Vec<_>>();
- crate::tui::overlay::picker(
- frame,
- area,
- &items,
- &mut state.player_picker_state,
- crate::tui::overlay::PickerSpec {
- title: "Open with",
- confirm_label: "Open",
- minimum_width: 24,
- },
- theme,
- state.basic_terminal,
- );
- }
-
if state.show_season_download_confirm {
let summary = season_confirm_summary(state);
let lines: Vec<Line<'_>> = summary
@@ -2150,10 +2116,8 @@ mod tests {
.map(|cell| cell.symbol())
.collect::<String>();
- // Section header clean styling
assert!(content.contains("1080p · 2 options"));
assert!(content.contains("720p · 1 option"));
- // Stream rows content
assert!(content.contains("1080p"));
assert!(content.contains("1.0GB"));
assert!(content.contains("HEVC"));
@@ -2249,7 +2213,6 @@ mod tests {
let theme = Theme::mocha();
let mut state = AppState::default();
- // Streams pane with subtitles
state.details_pane = crate::tui::state::DetailsPane::Streams;
state.subtitle_list = vec![("English".to_string(), "http://sub".to_string())];
let (primary, secondary) = details_footer(&state, &theme, 100);
@@ -2263,7 +2226,6 @@ mod tests {
assert!(footer_text.contains("[s] Subtitles"));
assert!(footer_text.contains("[Esc] Back"));
- // Seasons pane
state.details_pane = crate::tui::state::DetailsPane::Seasons;
let (primary, secondary) = details_footer(&state, &theme, 100);
let mut all_spans = primary;
@@ -2275,7 +2237,6 @@ mod tests {
assert!(footer_text.contains("[Tab] Streams"));
assert!(footer_text.contains("[Esc] Back"));
- // Episodes pane
state.details_pane = crate::tui::state::DetailsPane::Episodes;
let (primary, secondary) = details_footer(&state, &theme, 100);
let mut all_spans = primary;
diff --git a/src/tui/screens/help.rs b/src/tui/screens/help.rs
index 3a539aa..c5ee6bb 100644
--- a/src/tui/screens/help.rs
+++ b/src/tui/screens/help.rs
@@ -235,6 +235,10 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
" System & Settings",
theme.header.add_modifier(ratatui::style::Modifier::BOLD),
)]));
+ help_text.push(Line::from(vec![
+ Span::styled(" /settings ", theme.header),
+ Span::styled("Preferences, Modes & Configuration", theme.text),
+ ]));
help_text.push(Line::from(vec![
Span::styled(" /theme ", theme.header),
Span::styled("Change Color Theme", theme.text),
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 38eac4a..f3b4d4c 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -130,12 +130,12 @@ pub fn landing_split(
.constraints([
Constraint::Length(top_pad),
Constraint::Length(logo_height),
- Constraint::Length(1), // version
+ Constraint::Length(1),
Constraint::Length(header_gap),
- Constraint::Length(3), // search
+ Constraint::Length(3),
Constraint::Length(favorites_gap),
- Constraint::Min(0), // favorites deck
- Constraint::Length(1), // streamlined bottom bar
+ Constraint::Min(0),
+ Constraint::Length(1),
])
.split(area);
(
@@ -523,9 +523,9 @@ pub(crate) fn render_favorites_landing(
let left_margin = " ";
let right_margin = " ";
let tag_len = crate::tui::text::width(&right_tag);
- let pointer_len = 3; // "▌ " or "> " or " "
- let margins_len = 2 + 1; // left_margin (2) + right_margin (1)
- let fixed_overhead = margins_len + pointer_len + tag_len; // 6 + tag_len
+ let pointer_len = 3;
+ let margins_len = 3;
+ let fixed_overhead = margins_len + pointer_len + tag_len;
let max_title_width = (inner_area.width as usize).saturating_sub(fixed_overhead + 1);
let truncated_title = crate::tui::text::truncate_width(&item.title, max_title_width);
@@ -648,7 +648,10 @@ fn render_search_bar(
landing: bool,
) {
if landing {
- let border_style = if state.input_mode == InputMode::Editing {
+ let modal_active = state.has_active_modal();
+ let border_style = if modal_active {
+ theme.muted
+ } else if state.input_mode == InputMode::Editing {
theme.border_focus
} else {
theme.surface1
@@ -681,7 +684,38 @@ fn render_search_bar(
};
let is_query_empty = state.search_query.is_empty();
- let (pill_text, pill_style) = if !is_query_empty {
+ let (pill_text, pill_style) = if modal_active {
+ let text = if !is_query_empty {
+ if is_ultra_compact {
+ "[Enter]".to_string()
+ } else {
+ "[Enter] Search".to_string()
+ }
+ } else if state.is_tv_mode {
+ if is_ultra_compact {
+ "[TV]".to_string()
+ } else {
+ let sep = if state.basic_terminal { "-" } else { "·" };
+ format!("[Live TV {sep} {ctrl_t}]")
+ }
+ } else if state.is_addon_mode {
+ if is_ultra_compact {
+ "[Addons]".to_string()
+ } else {
+ let sep = if state.basic_terminal { "-" } else { "·" };
+ format!("[Addons {sep} {ctrl_p}]")
+ }
+ } else {
+ let label = state.active_provider.label();
+ if is_ultra_compact {
+ format!("[{label}]")
+ } else {
+ let sep = if state.basic_terminal { "-" } else { "·" };
+ format!("[{label} {sep} {ctrl_p}]")
+ }
+ };
+ (text, theme.text_dim)
+ } else if !is_query_empty {
if is_ultra_compact {
("[Enter]".to_string(), theme.accent)
} else {
@@ -747,7 +781,14 @@ fn render_search_bar(
let prefix = if state.basic_terminal { "> " } else { "❯ " };
let prefix_width = crate::tui::text::width(prefix) as u16;
let editing = view == SearchViewState::Editing;
- let real_cursor = editing && show_cursor && !state.basic_terminal;
+ let real_cursor = editing && show_cursor && !state.basic_terminal && !modal_active;
+ let prefix_style = if modal_active {
+ theme.text_dim
+ } else if editing {
+ theme.accent
+ } else {
+ theme.text_dim
+ };
let search_line = if is_query_empty {
let placeholder_text = if state.is_tv_mode {
@@ -758,21 +799,21 @@ fn render_search_bar(
"Search movies and series…"
};
- if editing {
+ if editing && !modal_active {
let cursor_str = if show_cursor { "█" } else { " " };
Line::from(vec![
- Span::styled(prefix, theme.accent),
+ Span::styled(prefix, prefix_style),
Span::styled(cursor_str, theme.accent),
Span::raw(" "),
Span::styled(placeholder_text, theme.text_dim),
])
} else {
Line::from(vec![
- Span::styled(prefix, theme.accent),
+ Span::styled(prefix, prefix_style),
Span::styled(placeholder_text, theme.text_dim),
])
}
- } else if editing && !real_cursor {
+ } else if editing && !real_cursor && !modal_active {
let segments = state.search_query.graphemes();
let cursor = state.search_query.cursor();
let cursor_char = if show_cursor {
@@ -789,15 +830,20 @@ fn render_search_bar(
String::new()
};
Line::from(vec![
- Span::styled(prefix, theme.accent),
+ Span::styled(prefix, prefix_style),
Span::styled(before, theme.text),
Span::styled(cursor_char, theme.accent),
Span::styled(after, theme.text),
])
} else {
+ let text_style = if modal_active {
+ theme.text_dim
+ } else {
+ theme.text
+ };
Line::from(vec![
- Span::styled(prefix, theme.accent),
- Span::styled(state.search_query.as_str(), theme.text),
+ Span::styled(prefix, prefix_style),
+ Span::styled(state.search_query.as_str(), text_style),
])
};
@@ -1035,14 +1081,25 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
])
.split(vertical_chunks[rows.version]);
+ let modal_active = state.has_active_modal() || state.show_settings_popup;
+ let logo_style = if modal_active {
+ theme.overlay0
+ } else {
+ theme.title
+ };
let title_art = Paragraph::new(logo_text)
.alignment(Alignment::Left)
- .style(theme.title);
+ .style(logo_style);
frame.render_widget(title_art, horizontal_chunks[1]);
+ let version_style = if modal_active {
+ theme.muted
+ } else {
+ theme.text_dim
+ };
let version = Paragraph::new(format!("v{}", env!("CARGO_PKG_VERSION")))
.alignment(Alignment::Right)
- .style(theme.text_dim);
+ .style(version_style);
frame.render_widget(version, version_chunks[1]);
let card_width = search_deck_width(area, state, true);
@@ -1091,21 +1148,21 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let current_mode = state.mode();
let mut bar_spans: Vec<Span> = Vec::new();
-
- if state.streaming_enabled {
- let is_active = current_mode == crate::tui::state::AppMode::Streaming;
- bar_spans.push(Span::styled("[", theme.text_dim));
- bar_spans.push(Span::styled(&ctrl_s, theme.shortcut));
- bar_spans.push(Span::styled("] ", theme.text_dim));
- bar_spans.push(Span::styled(
- "Stream",
- if is_active {
- theme.highlight.add_modifier(Modifier::BOLD)
- } else {
- theme.text_dim
- },
- ));
- }
+ let shortcut_style = if modal_active {
+ theme.muted
+ } else {
+ theme.shortcut
+ };
+ let bracket_style = if modal_active {
+ theme.muted
+ } else {
+ theme.text_dim
+ };
+ let text_style = if modal_active {
+ theme.muted
+ } else {
+ theme.text_dim
+ };
let sep = if state.basic_terminal {
" - "
@@ -1115,57 +1172,50 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
" · "
};
- if state.tv_enabled {
+ if state.streaming_enabled && current_mode != crate::tui::state::AppMode::Streaming {
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled(&ctrl_s, shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ bar_spans.push(Span::styled("Stream", text_style));
+ }
+
+ if state.tv_enabled && current_mode != crate::tui::state::AppMode::Tv {
if !bar_spans.is_empty() {
bar_spans.push(Span::raw(sep));
}
- let is_active = current_mode == crate::tui::state::AppMode::Tv;
- bar_spans.push(Span::styled("[", theme.text_dim));
- bar_spans.push(Span::styled(&ctrl_t, theme.shortcut));
- bar_spans.push(Span::styled("] ", theme.text_dim));
- bar_spans.push(Span::styled(
- "TV",
- if is_active {
- theme.highlight.add_modifier(Modifier::BOLD)
- } else {
- theme.text_dim
- },
- ));
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled(&ctrl_t, shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ bar_spans.push(Span::styled("TV", text_style));
}
- if state.addons_enabled {
+ if state.addons_enabled && current_mode != crate::tui::state::AppMode::Addon {
if !bar_spans.is_empty() {
bar_spans.push(Span::raw(sep));
}
- let is_active = current_mode == crate::tui::state::AppMode::Addon;
- bar_spans.push(Span::styled("[", theme.text_dim));
- bar_spans.push(Span::styled(&ctrl_a, theme.shortcut));
- bar_spans.push(Span::styled("] ", theme.text_dim));
- bar_spans.push(Span::styled(
- "Addon",
- if is_active {
- theme.highlight.add_modifier(Modifier::BOLD)
- } else {
- theme.text_dim
- },
- ));
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled(&ctrl_a, shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
+ bar_spans.push(Span::styled("Addon", text_style));
}
- let util_gap = if compact_tabs { " " } else { " " };
- bar_spans.push(Span::raw(util_gap));
+ if !bar_spans.is_empty() {
+ let util_gap = if compact_tabs { " " } else { " " };
+ bar_spans.push(Span::raw(util_gap));
+ }
- bar_spans.push(Span::styled("[", theme.text_dim));
- bar_spans.push(Span::styled("?", theme.shortcut));
- bar_spans.push(Span::styled("] ", theme.text_dim));
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled("?", shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
if !ultra_compact_tabs {
- bar_spans.push(Span::styled("Help", theme.text_dim));
+ bar_spans.push(Span::styled("Help", text_style));
bar_spans.push(Span::raw(" "));
}
- bar_spans.push(Span::styled("[", theme.text_dim));
- bar_spans.push(Span::styled("q", theme.shortcut));
- bar_spans.push(Span::styled("] ", theme.text_dim));
+ bar_spans.push(Span::styled("[", bracket_style));
+ bar_spans.push(Span::styled("q", shortcut_style));
+ bar_spans.push(Span::styled("] ", bracket_style));
if !ultra_compact_tabs {
- bar_spans.push(Span::styled("Quit", theme.text_dim));
+ bar_spans.push(Span::styled("Quit", text_style));
}
let bottom_bar_area = vertical_chunks[rows.mode_row];
@@ -1477,7 +1527,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
type_tag = "Unknown".to_string();
}
- // Row 1: Title + Right-pinned Resolution Badge
let res_badge = if !is_history {
crate::tui::widgets::badge::extract_resolution(&res.title, None)
} else {
@@ -1536,7 +1585,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
);
}
- // Row 2 & Row 3 Metadata
let mut row2_spans = vec![ratatui::text::Span::raw(" ")];
let mut row3_spans = vec![ratatui::text::Span::raw(" ")];
@@ -2048,27 +2096,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
state.basic_terminal,
);
}
-
- if state.player_picker_popup {
- let items = state
- .available_players
- .iter()
- .map(|k| k.label().to_string())
- .collect::<Vec<_>>();
- crate::tui::overlay::picker(
- frame,
- area,
- &items,
- &mut state.player_picker_state,
- crate::tui::overlay::PickerSpec {
- title: "Open with",
- confirm_label: "Open",
- minimum_width: 24,
- },
- theme,
- state.basic_terminal,
- );
- }
}
fn suggestion_source_badge<'a>(
suggestion: &str,
@@ -2081,6 +2108,13 @@ fn suggestion_source_badge<'a>(
("[HISTORY]", theme.sapphire)
} else if suggestion.eq_ignore_ascii_case("/favorites") {
("[FAVORITES]", theme.rating)
+ } else if suggestion.eq_ignore_ascii_case("/settings")
+ || suggestion.eq_ignore_ascii_case("/config")
+ || suggestion.eq_ignore_ascii_case("/preferences")
+ || suggestion.eq_ignore_ascii_case("/pref")
+ || suggestion.eq_ignore_ascii_case("/options")
+ {
+ ("[SETTINGS]", theme.teal)
} else {
("[CMD]", theme.teal)
}
@@ -2468,7 +2502,6 @@ mod tests {
let normal_area = Rect::new(0, 0, 90, 24);
let wide_area = Rect::new(0, 0, 120, 24);
- // Landing widths (54 on compact, 64 on standard/wide)
let w_compact_empty = search_deck_width(compact_area, &state, true);
let w_normal_empty = search_deck_width(normal_area, &state, true);
let w_wide_empty = search_deck_width(wide_area, &state, true);
@@ -2476,7 +2509,6 @@ mod tests {
assert_eq!(w_normal_empty, 64);
assert_eq!(w_wide_empty, 64);
- // Changing query does NOT jump landing search deck width
state.search_query = "Inception 2010 1080p".into();
assert_eq!(search_deck_width(compact_area, &state, true), 54);
assert_eq!(search_deck_width(normal_area, &state, true), 64);
@@ -2542,15 +2574,10 @@ mod tests {
rendered.push('\n');
}
- // Block framing header with star
assert!(rendered.contains("─ ★ Favorites"));
- // First selected item has leading margin, pointer, and title aligned under header
assert!(rendered.contains(" ▌ Favorite Movie 0"));
- // Unselected items have leading margin and spaces
assert!(rendered.contains(" Favorite Movie 1"));
- // Right tag is rendered with trailing margin before border
assert!(rendered.contains("2024 Movie "));
- // Overflow pill is rendered
assert!(rendered.contains("[ +5 more · /favorites ]"));
}
#[test]
@@ -2593,15 +2620,10 @@ mod tests {
rendered.push('\n');
}
- // Basic terminal header with ASCII asterisk
assert!(rendered.contains("- * Favorites"));
- // First selected item has leading margin, ASCII pointer, and title aligned under header
assert!(rendered.contains(" > Favorite Movie 0"));
- // Unselected items have leading margin and spaces
assert!(rendered.contains(" Favorite Movie 1"));
- // Right tag is rendered with trailing margin before border
assert!(rendered.contains("2024 Movie "));
- // Overflow pill uses ASCII hyphen separator
assert!(rendered.contains("[ +5 more - /favorites ]"));
}
@@ -2639,7 +2661,6 @@ mod tests {
state.search_list_state.select(Some(0));
let theme = Theme::mocha();
- // Normal mode drawing (active highlight)
terminal
.draw(|frame| {
let area = Rect::new(0, 0, 100, 30);
@@ -2647,7 +2668,6 @@ mod tests {
})
.unwrap();
- // Editing mode drawing (dimmed selection)
state.input_mode = InputMode::Editing;
terminal
.draw(|frame| {
@@ -2687,14 +2707,12 @@ mod tests {
}
rendered.push('\n');
}
- // 3-Row Search Card Frame & Prompt
assert!(rendered.contains('❯'));
assert!(rendered.contains("Search movies and series…"));
assert!(rendered.contains("[MovieBox"));
assert!(rendered.contains(&crate::tui::text::ctrl_key("P")));
- // Streamlined 1-line Bottom Bar
- assert!(rendered.contains("Stream"));
+ assert!(!rendered.contains("Stream"));
assert!(rendered.contains("TV"));
assert!(rendered.contains("Addon"));
assert!(rendered.contains("Quit"));
@@ -2739,11 +2757,9 @@ mod tests {
rendered.push('\n');
}
- // Header & Favorite items
assert!(rendered.contains("Favorites"));
assert!(rendered.contains("Interstellar"));
assert!(rendered.contains("2014 Movie") || rendered.contains("2014 Series"));
- // Overflow
assert!(rendered.contains("more · /favorites"));
}
@@ -2784,7 +2800,6 @@ mod tests {
let mut terminal = Terminal::new(backend).unwrap();
let theme = Theme::mocha();
- // TV Mode
let mut tv_state = AppState {
is_tv_mode: true,
basic_terminal: false,
@@ -2806,7 +2821,6 @@ mod tests {
assert!(tv_rendered.contains("[Live TV"));
assert!(tv_rendered.contains("Search live channels…"));
- // Addon Mode
let mut addon_state = AppState {
is_addon_mode: true,
basic_terminal: false,
diff --git a/src/tui/state.rs b/src/tui/state.rs
index c235f05..625722a 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -30,6 +30,78 @@ pub enum InputMode {
Normal,
Editing,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum SettingsCategory {
+ #[default]
+ General,
+ ContentModes,
+ Appearance,
+ StorageInfo,
+}
+
+impl SettingsCategory {
+ pub const ALL: [Self; 4] = [
+ Self::General,
+ Self::ContentModes,
+ Self::Appearance,
+ Self::StorageInfo,
+ ];
+
+ pub fn title(self) -> &'static str {
+ match self {
+ Self::General => "General",
+ Self::ContentModes => "Content Modes",
+ Self::Appearance => "Appearance",
+ Self::StorageInfo => "Maintenance",
+ }
+ }
+
+ pub fn badge(self) -> &'static str {
+ match self {
+ Self::General => "GEN",
+ Self::ContentModes => "MODES",
+ Self::Appearance => "THEME",
+ Self::StorageInfo => "MAINT",
+ }
+ }
+
+ pub fn row_count(self) -> usize {
+ match self {
+ Self::General => 3,
+ Self::ContentModes => 4,
+ Self::Appearance => 1,
+ Self::StorageInfo => 3,
+ }
+ }
+ pub fn next(self) -> Self {
+ match self {
+ Self::General => Self::ContentModes,
+ Self::ContentModes => Self::Appearance,
+ Self::Appearance => Self::StorageInfo,
+ Self::StorageInfo => Self::General,
+ }
+ }
+
+ pub fn previous(self) -> Self {
+ match self {
+ Self::General => Self::StorageInfo,
+ Self::ContentModes => Self::General,
+ Self::Appearance => Self::ContentModes,
+ Self::StorageInfo => Self::Appearance,
+ }
+ }
+}
+
+pub fn settings_player_label(choice: Option<&str>) -> &'static str {
+ match choice {
+ None | Some("auto") => "None",
+ Some("mpv") => "mpv",
+ Some("vlc") => "VLC",
+ Some("iina") => "IINA",
+ Some("android") => "Android Player",
+ Some(_) => "Custom",
+ }
+}
pub use crate::models::{
BrowseMetric, BrowseMetrics, BrowsePreset, Notification, NotificationKind, SearchResult,
@@ -129,6 +201,10 @@ pub struct AppState {
pub active_browse_preset: Option<BrowsePreset>,
pub active_addon_catalog: Option<crate::providers::addons::models::AddonCatalogTarget>,
pub browse_metrics: std::collections::HashMap<String, BrowseMetrics>,
+ pub show_settings_popup: bool,
+ pub settings_category: SettingsCategory,
+ pub settings_selected_row: usize,
+ pub settings_download_dir_input: Option<crate::tui::text::TextInputBuffer>,
pub poster_protocol: Option<(ratatui::layout::Rect, ratatui_image::protocol::Protocol)>,
pub image_picker: Option<ratatui_image::picker::Picker>,
@@ -157,6 +233,7 @@ pub struct AppState {
pub player_picker_link: Option<String>,
pub player_picker_subtitle: Option<String>,
pub player_picker_playback: Option<crate::providers::models::PlaybackSource>,
+ pub settings_player_picker: bool,
pub available_players: Vec<PlayerKind>,
pub default_player: Option<String>,
pub is_loading: bool,
@@ -286,6 +363,11 @@ impl Default for AppState {
active_browse_preset: None,
active_addon_catalog: None,
browse_metrics: std::collections::HashMap::new(),
+ show_settings_popup: false,
+ settings_category: SettingsCategory::General,
+ settings_selected_row: 0,
+ settings_download_dir_input: None,
+
poster_protocol: None,
image_picker: None,
image_supported: crate::tui::terminal::should_query_images(),
@@ -311,6 +393,7 @@ impl Default for AppState {
player_picker_link: None,
player_picker_subtitle: None,
player_picker_playback: None,
+ settings_player_picker: false,
available_players: Vec::new(),
default_player: None,
dirty: true,
@@ -522,8 +605,6 @@ impl AppState {
const FAILED_POSTER_TTL_SECS: u64 = 600;
- /// Returns true when this poster failed recently; expired failures are
- /// evicted so the fetch can be retried.
pub fn failed_poster_recently(&mut self, id: &str) -> bool {
match self.failed_posters.peek(id) {
Some(failed_at) if failed_at.elapsed().as_secs() < Self::FAILED_POSTER_TTL_SECS => true,
@@ -538,6 +619,7 @@ impl AppState {
self.show_help
|| self.show_theme_popup
|| self.show_browse_popup
+ || self.show_settings_popup
|| self.addon_manager_popup
|| self.tv_config_popup
|| self.player_picker_popup
@@ -615,6 +697,138 @@ impl AppState {
_ => "...",
}
}
+ pub fn settings_next_category(&mut self) {
+ self.settings_category = self.settings_category.next();
+ self.settings_selected_row = 0;
+ self.settings_download_dir_input = None;
+ }
+
+ pub fn settings_previous_category(&mut self) {
+ self.settings_category = self.settings_category.previous();
+ self.settings_selected_row = 0;
+ self.settings_download_dir_input = None;
+ }
+
+ pub fn settings_select_category(&mut self, cat: SettingsCategory) {
+ if self.settings_category != cat {
+ self.settings_category = cat;
+ self.settings_selected_row = 0;
+ self.settings_download_dir_input = None;
+ }
+ }
+
+ pub fn settings_row_up(&mut self) {
+ let count = self.settings_category.row_count();
+ if count > 0 {
+ self.settings_selected_row = (self.settings_selected_row + count - 1) % count;
+ }
+ }
+
+ pub fn settings_row_down(&mut self) {
+ let count = self.settings_category.row_count();
+ if count > 0 {
+ self.settings_selected_row = (self.settings_selected_row + 1) % count;
+ }
+ }
+
+ pub fn ensure_default_player(&mut self) {
+ if (self.default_player.is_none() || self.default_player.as_deref() == Some("auto"))
+ && let Some(first) = self.available_players.first()
+ {
+ self.default_player = Some(first.config_key().to_string());
+ }
+ }
+
+ pub fn settings_player_choices(&self) -> Vec<&str> {
+ let mut choices: Vec<&str> = Vec::with_capacity(self.available_players.len());
+ for player in &self.available_players {
+ let key = player.config_key();
+ if !choices.iter().any(|&c| c.eq_ignore_ascii_case(key)) {
+ choices.push(key);
+ }
+ }
+ choices
+ }
+
+ pub fn cycle_settings_player(&mut self, forward: bool) {
+ let choices = self.settings_player_choices();
+ if choices.is_empty() {
+ return;
+ }
+ let current_key = self.default_player.as_deref();
+ let current_idx = current_key
+ .and_then(|k| choices.iter().position(|&opt| opt.eq_ignore_ascii_case(k)))
+ .unwrap_or(0);
+
+ let total = choices.len();
+ let next_idx = if forward {
+ (current_idx + 1) % total
+ } else {
+ (current_idx + total - 1) % total
+ };
+
+ self.default_player = Some(choices[next_idx].to_string());
+ }
+
+ pub fn cycle_settings_theme(&mut self, forward: bool) -> String {
+ let themes = crate::tui::theme::AVAILABLE_THEMES;
+ let total = themes.len();
+ let current_idx = themes
+ .iter()
+ .position(|&t| t.eq_ignore_ascii_case(&self.active_theme_kind))
+ .unwrap_or(0);
+
+ let next_idx = if forward {
+ (current_idx + 1) % total
+ } else {
+ (current_idx + total - 1) % total
+ };
+
+ let next_theme = themes[next_idx].to_string();
+ self.active_theme_kind = next_theme.clone();
+ self.theme_is_auto = false;
+ next_theme
+ }
+
+ pub fn can_disable_streaming_mode(&self) -> bool {
+ self.tv_enabled || self.addons_enabled
+ }
+
+ pub fn can_disable_tv_mode(&self) -> bool {
+ self.streaming_enabled || self.addons_enabled
+ }
+
+ pub fn can_disable_addons_mode(&self) -> bool {
+ self.streaming_enabled || self.tv_enabled
+ }
+ pub fn expand_download_path(raw: &str) -> Option<std::path::PathBuf> {
+ let clean = raw.trim_matches(|c| c == '\'' || c == '"').trim();
+ if clean.is_empty()
+ || clean.eq_ignore_ascii_case("default")
+ || clean.eq_ignore_ascii_case("reset")
+ || clean == "<path>"
+ || clean == "path"
+ || clean == "<dir>"
+ || clean == "dir"
+ {
+ return None;
+ }
+ let pb = if let Some(stripped) = clean
+ .strip_prefix("~/")
+ .or_else(|| clean.strip_prefix("~\\"))
+ {
+ if let Some(home) = dirs::home_dir() {
+ home.join(stripped)
+ } else {
+ std::path::PathBuf::from(clean)
+ }
+ } else if clean == "~" {
+ dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from(clean))
+ } else {
+ std::path::PathBuf::from(clean)
+ };
+ Some(pb)
+ }
}
pub fn cycle_list_selection(state: &mut ListState, total_items: usize, forward: bool) {
@@ -858,4 +1072,23 @@ mod tests {
state.input_mode = InputMode::Normal;
assert!(state.favorites_landing_visible());
}
+
+ #[test]
+ fn test_cycle_settings_player_dynamic_detection() {
+ let mut state = AppState {
+ available_players: vec![PlayerKind::Mpv],
+ ..Default::default()
+ };
+ assert_eq!(state.settings_player_choices(), vec!["mpv"]);
+
+ state.default_player = None;
+ state.cycle_settings_player(true);
+ assert_eq!(state.default_player.as_deref(), Some("mpv"));
+
+ state.cycle_settings_player(true);
+ assert_eq!(state.default_player.as_deref(), Some("mpv"));
+
+ state.cycle_settings_player(false);
+ assert_eq!(state.default_player.as_deref(), Some("mpv"));
+ }
}
diff --git a/src/tui/theme.rs b/src/tui/theme.rs
index 1dca98a..59a2051 100644
--- a/src/tui/theme.rs
+++ b/src/tui/theme.rs
@@ -130,6 +130,14 @@ impl ColorSupport {
let term_program = std::env::var("TERM_PROGRAM").unwrap_or_default();
classify_terminal(&colorterm, &term, &term_program)
}
+ pub fn label(&self) -> &'static str {
+ match self {
+ ColorSupport::Truecolor => "TrueColor (24-bit RGB)",
+ ColorSupport::Color256 => "256 Colors (8-bit ANSI)",
+ ColorSupport::Basic => "Basic (16 Colors)",
+ ColorSupport::NoColor => "No Color (Monochrome)",
+ }
+ }
}
pub(crate) fn classify_terminal(colorterm: &str, term: &str, term_program: &str) -> ColorSupport {
diff --git a/src/tui/widgets/mod.rs b/src/tui/widgets/mod.rs
index 7f16b16..62c29a6 100644
--- a/src/tui/widgets/mod.rs
+++ b/src/tui/widgets/mod.rs
@@ -2,6 +2,7 @@ pub mod badge;
pub mod input;
pub mod modal;
pub mod scrollbar;
+pub mod settings;
pub use badge::{
MediaTags, extract_media_tags, render_media_tag_spans, resolution_badge_spans, resolution_label,
diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs
new file mode 100644
index 0000000..a9a7eca
--- /dev/null
+++ b/src/tui/widgets/settings.rs
@@ -0,0 +1,1049 @@
+use ratatui::{
+ Frame,
+ layout::{Alignment, Constraint, Layout, Rect},
+ style::{Modifier, Style},
+ text::{Line, Span},
+ widgets::{Block, Borders, Paragraph},
+};
+
+use crate::tui::{
+ overlay::{self, key_hint},
+ state::{AppState, SettingsCategory, settings_player_label},
+ theme::{ColorSupport, Theme},
+ widgets::ModalFrame,
+};
+
+pub fn category_tab_text(cat: SettingsCategory, _is_active: bool, _basic_terminal: bool) -> String {
+ cat.title().to_string()
+}
+
+pub fn category_tab_rects(
+ tabs_area: Rect,
+ _basic_terminal: bool,
+ _active_cat: SettingsCategory,
+) -> Vec<(SettingsCategory, Rect)> {
+ let mut results = Vec::new();
+ let mut current_x = tabs_area.x;
+
+ for cat in SettingsCategory::ALL {
+ let width = crate::tui::text::width(cat.title()) as u16;
+ if current_x + width <= tabs_area.right() {
+ results.push((
+ cat,
+ Rect {
+ x: current_x,
+ y: tabs_area.y,
+ width,
+ height: 2,
+ },
+ ));
+ }
+ current_x = current_x.saturating_add(width).saturating_add(5);
+ }
+ results
+}
+
+pub fn settings_category_tab_at(
+ popup_area: Rect,
+ col: u16,
+ row: u16,
+ basic_terminal: bool,
+ active_cat: SettingsCategory,
+) -> Option<SettingsCategory> {
+ if popup_area.width < 4 || popup_area.height < 4 {
+ return None;
+ }
+ let inner_y = popup_area.y + 1;
+ if row != inner_y && row != inner_y + 1 {
+ return None;
+ }
+ let tabs_area = Rect {
+ x: popup_area.x + 3,
+ y: inner_y,
+ width: popup_area.width.saturating_sub(6),
+ height: 2,
+ };
+ for (cat, rect) in category_tab_rects(tabs_area, basic_terminal, active_cat) {
+ if col >= rect.x && col < rect.right() && row >= rect.y && row < rect.bottom() {
+ return Some(cat);
+ }
+ }
+ None
+}
+
+pub fn settings_row_rects(popup_area: Rect, category: SettingsCategory) -> Vec<Rect> {
+ if popup_area.width < 4 || popup_area.height < 6 {
+ return Vec::new();
+ }
+ let inner = Rect {
+ x: popup_area.x + 1,
+ y: popup_area.y + 1,
+ width: popup_area.width.saturating_sub(2),
+ height: popup_area.height.saturating_sub(2),
+ };
+ let rows_height = (category.row_count() as u16 * 2).min(inner.height.saturating_sub(5));
+ let sections = Layout::vertical([
+ Constraint::Length(2),
+ Constraint::Length(1),
+ Constraint::Length(rows_height),
+ Constraint::Min(0),
+ Constraint::Length(2),
+ ])
+ .split(inner);
+ let rows_area = sections[2];
+ let card_x = popup_area.x + 3;
+ let card_width = popup_area.width.saturating_sub(6);
+ let row_count = category.row_count();
+ let mut rects = Vec::with_capacity(row_count);
+ for i in 0..row_count {
+ let y = rows_area.y + (i as u16 * 2);
+ if y.saturating_add(1) < rows_area.bottom() {
+ rects.push(Rect {
+ x: card_x,
+ y,
+ width: card_width,
+ height: 2,
+ });
+ } else if y < rows_area.bottom() {
+ rects.push(Rect {
+ x: card_x,
+ y,
+ width: card_width,
+ height: 1,
+ });
+ }
+ }
+ rects
+}
+
+pub fn settings_row_at(
+ popup_area: Rect,
+ category: SettingsCategory,
+ col: u16,
+ row: u16,
+) -> Option<usize> {
+ for (idx, rect) in settings_row_rects(popup_area, category)
+ .into_iter()
+ .enumerate()
+ {
+ if row >= rect.y && row < rect.bottom() && col >= rect.x && col < rect.right() {
+ return Some(idx);
+ }
+ }
+ None
+}
+
+pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme) {
+ let popup_area = overlay::settings_modal_layout(area, state.settings_category);
+ let title = " Settings & Preferences ";
+
+ let inner = ModalFrame::new(title, theme, state.basic_terminal).render(frame, popup_area, area);
+ if inner.width < 10 || inner.height < 4 {
+ return;
+ }
+
+ let rows_height =
+ (state.settings_category.row_count() as u16 * 2).min(inner.height.saturating_sub(5));
+ let sections = Layout::vertical([
+ Constraint::Length(2),
+ Constraint::Length(1),
+ Constraint::Length(rows_height),
+ Constraint::Min(0),
+ Constraint::Length(2),
+ ])
+ .split(inner);
+
+ render_tabs(frame, sections[0], popup_area, state, theme);
+ render_category_description(frame, sections[1], popup_area, state, theme);
+ render_category_rows(frame, sections[2], popup_area, state, theme);
+ render_footer(frame, sections[4], state, theme);
+}
+
+fn render_tabs(frame: &mut Frame, area: Rect, popup_area: Rect, state: &AppState, theme: &Theme) {
+ let mut line0_spans = Vec::new();
+ let mut line1_spans = Vec::new();
+
+ for (i, cat) in SettingsCategory::ALL.iter().enumerate() {
+ if i > 0 {
+ line0_spans.push(Span::raw(" "));
+ line1_spans.push(Span::raw(" "));
+ }
+ let is_active = *cat == state.settings_category;
+ let title = cat.title();
+ let width = crate::tui::text::width(title);
+
+ if is_active {
+ let title_style = if state.basic_terminal {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.accent.add_modifier(Modifier::BOLD)
+ };
+ line0_spans.push(Span::styled(title, title_style));
+
+ let underline_style = if state.basic_terminal {
+ theme.text
+ } else {
+ theme.accent
+ };
+ line1_spans.push(Span::styled("─".repeat(width), underline_style));
+ } else {
+ let title_style = if state.basic_terminal {
+ theme.text_dim
+ } else {
+ theme.subtext1
+ };
+ line0_spans.push(Span::styled(title, title_style));
+ line1_spans.push(Span::raw(" ".repeat(width)));
+ }
+ }
+
+ let tabs_render_area = Rect {
+ x: popup_area.x + 3,
+ y: area.y,
+ width: popup_area.width.saturating_sub(6),
+ height: area.height.min(2),
+ };
+ let lines = if area.height >= 2 {
+ vec![Line::from(line0_spans), Line::from(line1_spans)]
+ } else {
+ vec![Line::from(line0_spans)]
+ };
+ frame.render_widget(Paragraph::new(lines), tabs_render_area);
+}
+
+fn category_subtitle(cat: SettingsCategory) -> &'static str {
+ match cat {
+ SettingsCategory::General => "Application defaults & media playback settings",
+ SettingsCategory::ContentModes => "Toggle active content providers & streaming sources",
+ SettingsCategory::Appearance => "UI color theme, palette previews & terminal depth",
+ SettingsCategory::StorageInfo => "Cache cleanup, release updates & diagnostics",
+ }
+}
+
+fn render_category_description(
+ frame: &mut Frame,
+ area: Rect,
+ popup_area: Rect,
+ state: &AppState,
+ theme: &Theme,
+) {
+ let desc_render_area = Rect {
+ x: popup_area.x + 3,
+ y: area.y,
+ width: popup_area.width.saturating_sub(6),
+ height: area.height.min(1),
+ };
+ let desc_style = if state.basic_terminal {
+ theme.text_dim
+ } else {
+ theme.overlay1
+ };
+ let line = Line::from(vec![Span::styled(
+ category_subtitle(state.settings_category),
+ desc_style,
+ )]);
+ frame.render_widget(Paragraph::new(line), desc_render_area);
+}
+
+fn render_category_rows(
+ frame: &mut Frame,
+ area: Rect,
+ popup_area: Rect,
+ state: &AppState,
+ theme: &Theme,
+) {
+ let rows_area = Rect {
+ x: popup_area.x + 3,
+ y: area.y,
+ width: popup_area.width.saturating_sub(6),
+ height: area.height,
+ };
+ match state.settings_category {
+ SettingsCategory::General => render_general_settings(frame, rows_area, state, theme),
+ SettingsCategory::ContentModes => {
+ render_content_modes_settings(frame, rows_area, state, theme)
+ }
+ SettingsCategory::Appearance => render_appearance_settings(frame, rows_area, state, theme),
+ SettingsCategory::StorageInfo => render_storage_settings(frame, rows_area, state, theme),
+ }
+}
+
+struct SettingRow<'a> {
+ is_selected: bool,
+ label: &'a str,
+ subtext: &'a str,
+ value_spans: Vec<Span<'a>>,
+}
+
+fn on_off_spans<'a>(enabled: bool, theme: &Theme, basic_terminal: bool) -> Vec<Span<'a>> {
+ if enabled {
+ vec![Span::styled(
+ "ON",
+ if basic_terminal {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.rating.add_modifier(Modifier::BOLD)
+ },
+ )]
+ } else {
+ vec![Span::styled(
+ "OFF",
+ if basic_terminal {
+ theme.text_dim
+ } else {
+ theme.subtext1
+ },
+ )]
+ }
+}
+
+fn render_row(
+ frame: &mut Frame,
+ area: Rect,
+ row: SettingRow<'_>,
+ theme: &Theme,
+ basic_terminal: bool,
+) {
+ if area.height == 0 || area.width == 0 {
+ return;
+ }
+ let cursor = if row.is_selected {
+ if basic_terminal { "> " } else { "▸ " }
+ } else {
+ " "
+ };
+
+ let cursor_style = if row.is_selected {
+ if basic_terminal {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.accent.add_modifier(Modifier::BOLD)
+ }
+ } else {
+ Style::default()
+ };
+
+ let label_style = if row.is_selected {
+ theme.highlight.add_modifier(Modifier::BOLD)
+ } else {
+ theme.text
+ };
+
+ let row_bg = if row.is_selected && !basic_terminal {
+ Style::default().bg(theme.surface0.fg.unwrap_or(theme.base))
+ } else {
+ Style::default()
+ };
+
+ let cursor_width = crate::tui::text::width(cursor);
+ let label_width = crate::tui::text::width(row.label);
+ let total_left_width = cursor_width + label_width;
+
+ let right_width: usize = row
+ .value_spans
+ .iter()
+ .map(|s| crate::tui::text::width(&s.content))
+ .sum();
+
+ let right_margin = 1;
+ let pad = (area.width as usize).saturating_sub(total_left_width + right_width + right_margin);
+
+ let mut line1_spans = Vec::new();
+ line1_spans.push(Span::styled(cursor, cursor_style));
+ line1_spans.push(Span::styled(row.label, label_style));
+ if pad > 0 {
+ line1_spans.push(Span::raw(" ".repeat(pad)));
+ } else {
+ line1_spans.push(Span::raw(" "));
+ }
+ line1_spans.extend(row.value_spans);
+ line1_spans.push(Span::raw(" ".repeat(right_margin)));
+ let subtext_indent = " ";
+ let subtext_width = crate::tui::text::width(row.subtext);
+ let subtext_pad = (area.width as usize).saturating_sub(subtext_indent.len() + subtext_width);
+ let mut line2_spans = Vec::new();
+ line2_spans.push(Span::raw(subtext_indent));
+ line2_spans.push(Span::styled(
+ row.subtext,
+ if row.is_selected {
+ theme.subtext1
+ } else {
+ theme.overlay1
+ },
+ ));
+ if subtext_pad > 0 {
+ line2_spans.push(Span::raw(" ".repeat(subtext_pad)));
+ }
+
+ let lines = if area.height >= 2 {
+ vec![Line::from(line1_spans), Line::from(line2_spans)]
+ } else {
+ vec![Line::from(line1_spans)]
+ };
+
+ frame.render_widget(Paragraph::new(lines).style(row_bg), area);
+}
+
+fn render_general_settings(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
+ let row_rects = settings_row_rects_in_area(area, 3);
+
+ if let Some(&row_area) = row_rects.first() {
+ let is_selected = state.settings_selected_row == 0;
+ let value_spans = on_off_spans(state.auto_update, theme, state.basic_terminal);
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Automatic Updates",
+ subtext: "Check GitHub for new releases on startup",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(1) {
+ let is_selected = state.settings_selected_row == 1;
+ let player_name = if let Some(key) = state
+ .default_player
+ .as_deref()
+ .filter(|k| !k.is_empty() && *k != "auto")
+ {
+ settings_player_label(Some(key))
+ } else if let Some(first) = state.available_players.first() {
+ settings_player_label(Some(first.config_key()))
+ } else {
+ settings_player_label(None)
+ };
+ let value_spans = vec![Span::styled(
+ player_name,
+ if state.basic_terminal {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.accent.add_modifier(Modifier::BOLD)
+ },
+ )];
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Default Media Player",
+ subtext: "Preferred player launched for video streams",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(2) {
+ let is_selected = state.settings_selected_row == 2;
+ let value_spans = if let Some(input) = &state.settings_download_dir_input {
+ let cursor_char = if state.basic_terminal { "_" } else { "▌" };
+ let input_str = input.as_str();
+ let cursor_idx = input.cursor().min(input_str.len());
+ let (before, after) = input_str.split_at(cursor_idx);
+ let truncated_before = crate::tui::text::truncate_width(before, 26);
+ if state.basic_terminal {
+ vec![
+ Span::styled(truncated_before, theme.text),
+ Span::styled(cursor_char, theme.text.add_modifier(Modifier::BOLD)),
+ Span::styled(after, theme.text),
+ ]
+ } else {
+ let input_bg = theme.surface0.fg.unwrap_or(theme.base);
+ let input_style = Style::default()
+ .fg(theme
+ .text
+ .fg
+ .unwrap_or(theme.subtext1.fg.unwrap_or(theme.base)))
+ .bg(input_bg);
+ let cursor_style = theme.accent.add_modifier(Modifier::BOLD).bg(input_bg);
+ vec![
+ Span::styled(truncated_before, input_style),
+ Span::styled(cursor_char, cursor_style),
+ Span::styled(after, input_style),
+ ]
+ }
+ } else {
+ let path_str = state
+ .download_dir
+ .as_ref()
+ .map(crate::logging::sanitize_path)
+ .unwrap_or_else(|| {
+ crate::logging::sanitize_path(crate::service::resolve_download_dir(None))
+ });
+ let truncated = crate::tui::text::truncate_width(&path_str, 28);
+ vec![Span::styled(
+ truncated,
+ if state.basic_terminal {
+ theme.text_dim
+ } else {
+ theme.subtext1
+ },
+ )]
+ };
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Download Folder",
+ subtext: "Directory for saving downloaded videos & subtitles",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+}
+
+fn render_content_modes_settings(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
+ let row_rects = settings_row_rects_in_area(area, 4);
+
+ if let Some(&row_area) = row_rects.first() {
+ let is_selected = state.settings_selected_row == 0;
+ let value_spans = on_off_spans(state.streaming_enabled, theme, state.basic_terminal);
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Streaming Mode",
+ subtext: "MovieBox & 4KHDHub streaming catalog",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(1) {
+ let is_selected = state.settings_selected_row == 1;
+ let value_spans = on_off_spans(state.bdix_enabled, theme, state.basic_terminal);
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "BDIX FTP Mirrors",
+ subtext: "Local high-speed BDIX optical mirrors for streaming",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(2) {
+ let is_selected = state.settings_selected_row == 2;
+ let value_spans = on_off_spans(state.tv_enabled, theme, state.basic_terminal);
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Live TV Mode",
+ subtext: "Live IPTV channels and custom M3U playlists",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(3) {
+ let is_selected = state.settings_selected_row == 3;
+ let value_spans = on_off_spans(state.addons_enabled, theme, state.basic_terminal);
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Addon Mode",
+ subtext: "Community HTTP Stremio addons and metadata",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+}
+
+fn render_appearance_settings(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
+ let row_rects = settings_row_rects_in_area(area, 1);
+
+ let theme_name = if state.active_theme_kind.is_empty() {
+ "Mocha"
+ } else {
+ &state.active_theme_kind
+ };
+
+ if let Some(&row_area) = row_rects.first() {
+ let is_selected = state.settings_selected_row == 0;
+ let mut value_spans = vec![Span::styled(
+ format!("{theme_name} "),
+ theme.accent.add_modifier(Modifier::BOLD),
+ )];
+ value_spans.extend(Theme::palette_swatch_spans(
+ theme_name,
+ state.basic_terminal,
+ ));
+
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Theme",
+ subtext: "Active color theme and palette styling",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if area.height >= 5 {
+ let info_y = area.y + 3;
+ let info_area = Rect {
+ x: area.x,
+ y: info_y,
+ width: area.width,
+ height: area.bottom().saturating_sub(info_y),
+ };
+ let label = "Terminal Depth";
+ let value = ColorSupport::current().label();
+ let label_width = crate::tui::text::width(label);
+ let val_width = crate::tui::text::width(value);
+ let pad = (info_area.width as usize).saturating_sub(label_width + val_width);
+ let lines = vec![
+ Line::from(vec![
+ Span::styled(label, theme.text),
+ Span::raw(" ".repeat(pad)),
+ Span::styled(value, theme.subtext1),
+ ]),
+ Line::from(vec![Span::styled(
+ "Live preview: color switches take effect instantly",
+ theme.overlay1,
+ )]),
+ ];
+ frame.render_widget(Paragraph::new(lines), info_area);
+ }
+}
+
+fn render_storage_settings(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
+ let row_rects = settings_row_rects_in_area(area, 3);
+
+ if let Some(&row_area) = row_rects.first() {
+ let is_selected = state.settings_selected_row == 0;
+ let glyph = if state.basic_terminal { ">" } else { "▸" };
+ let value_spans = vec![Span::styled(
+ format!("Purge {glyph}"),
+ if state.basic_terminal {
+ if is_selected {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.text_dim
+ }
+ } else if is_selected {
+ theme.error.add_modifier(Modifier::BOLD)
+ } else {
+ theme.error
+ },
+ )];
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Clear Disk Cache",
+ subtext: "Remove temporary cached images and responses",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(1) {
+ let is_selected = state.settings_selected_row == 1;
+ let value_spans = if state.is_checking_updates {
+ vec![Span::styled(
+ "Checking...",
+ if state.basic_terminal {
+ theme.text_dim
+ } else {
+ theme.sapphire
+ },
+ )]
+ } else {
+ let glyph = if state.basic_terminal { ">" } else { "▸" };
+ vec![Span::styled(
+ format!("Check {glyph}"),
+ if state.basic_terminal {
+ if is_selected {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.text_dim
+ }
+ } else if is_selected {
+ theme.sapphire.add_modifier(Modifier::BOLD)
+ } else {
+ theme.sapphire
+ },
+ )]
+ };
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "Check for Updates",
+ subtext: "Query GitHub API for latest binary releases",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+
+ if let Some(&row_area) = row_rects.get(2) {
+ let is_selected = state.settings_selected_row == 2;
+ let glyph = if state.basic_terminal { "->" } else { "↗" };
+ let value_spans = vec![Span::styled(
+ format!("Open {glyph}"),
+ if state.basic_terminal {
+ if is_selected {
+ theme.text.add_modifier(Modifier::BOLD)
+ } else {
+ theme.text_dim
+ }
+ } else if is_selected {
+ theme.lavender.add_modifier(Modifier::BOLD)
+ } else {
+ theme.lavender
+ },
+ )];
+ render_row(
+ frame,
+ row_area,
+ SettingRow {
+ is_selected,
+ label: "GitHub Repository",
+ subtext: "Open project homepage in default web browser",
+ value_spans,
+ },
+ theme,
+ state.basic_terminal,
+ );
+ }
+}
+
+fn settings_row_rects_in_area(area: Rect, count: usize) -> Vec<Rect> {
+ let mut rects = Vec::with_capacity(count);
+ for i in 0..count {
+ let y = area.y + (i as u16 * 2);
+ if y.saturating_add(1) < area.bottom() {
+ rects.push(Rect {
+ x: area.x,
+ y,
+ width: area.width,
+ height: 2,
+ });
+ } else if y < area.bottom() {
+ rects.push(Rect {
+ x: area.x,
+ y,
+ width: area.width,
+ height: 1,
+ });
+ }
+ }
+ rects
+}
+
+fn render_footer(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
+ let footer_spans = if state.settings_download_dir_input.is_some() {
+ if state.basic_terminal {
+ vec![
+ Span::raw("[Enter] Save "),
+ Span::raw("[Esc] Cancel "),
+ Span::raw("[Backspace] Delete"),
+ ]
+ } else {
+ vec![
+ key_hint("Enter", "Save", theme),
+ Span::raw(" "),
+ key_hint("Esc", "Cancel", theme),
+ Span::raw(" "),
+ key_hint("Backspace", "Delete", theme),
+ ]
+ }
+ } else if state.basic_terminal {
+ if area.width >= 66 {
+ vec![
+ Span::raw("[Tab] Category "),
+ Span::raw("[↑↓] Move "),
+ Span::raw("[←→] Edit "),
+ Span::raw("[Enter] Select "),
+ Span::raw("[Esc] Close"),
+ ]
+ } else if area.width >= 60 {
+ vec![
+ Span::raw("[Tab] Category "),
+ Span::raw("[↑↓] Move "),
+ Span::raw("[←→] Edit "),
+ Span::raw("[Enter] Select "),
+ Span::raw("[Esc] Close"),
+ ]
+ } else if area.width >= 48 {
+ vec![
+ Span::raw("[Tab] Cat "),
+ Span::raw("[↑↓] Move "),
+ Span::raw("[←→] Edit "),
+ Span::raw("[Enter] Sel "),
+ Span::raw("[Esc] Close"),
+ ]
+ } else {
+ vec![
+ Span::raw("[Tab] Cat "),
+ Span::raw("[↑↓] "),
+ Span::raw("[←→] "),
+ Span::raw("[Enter] "),
+ Span::raw("[Esc] Close"),
+ ]
+ }
+ } else if area.width >= 66 {
+ vec![
+ key_hint("Tab", "Category", theme),
+ Span::raw(" "),
+ key_hint("↑↓", "Move", theme),
+ Span::raw(" "),
+ key_hint("←→", "Edit", theme),
+ Span::raw(" "),
+ key_hint("Enter", "Select", theme),
+ Span::raw(" "),
+ key_hint("Esc", "Close", theme),
+ ]
+ } else if area.width >= 60 {
+ vec![
+ key_hint("Tab", "Category", theme),
+ Span::raw(" "),
+ key_hint("↑↓", "Move", theme),
+ Span::raw(" "),
+ key_hint("←→", "Edit", theme),
+ Span::raw(" "),
+ key_hint("Enter", "Select", theme),
+ Span::raw(" "),
+ key_hint("Esc", "Close", theme),
+ ]
+ } else if area.width >= 48 {
+ vec![
+ key_hint("Tab", "Cat", theme),
+ Span::raw(" "),
+ key_hint("↑↓", "Move", theme),
+ Span::raw(" "),
+ key_hint("←→", "Edit", theme),
+ Span::raw(" "),
+ key_hint("Enter", "Sel", theme),
+ Span::raw(" "),
+ key_hint("Esc", "Close", theme),
+ ]
+ } else {
+ vec![
+ key_hint("Tab", "Cat", theme),
+ Span::raw(" "),
+ key_hint("↑↓", "", theme),
+ Span::raw(" "),
+ key_hint("←→", "", theme),
+ Span::raw(" "),
+ key_hint("Enter", "", theme),
+ Span::raw(" "),
+ key_hint("Esc", "Close", theme),
+ ]
+ };
+
+ let p = Paragraph::new(Line::from(footer_spans))
+ .alignment(Alignment::Center)
+ .block(
+ Block::default()
+ .borders(Borders::TOP)
+ .border_style(theme.muted),
+ );
+ frame.render_widget(p, area);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::{Terminal, backend::TestBackend};
+
+ #[test]
+ fn test_render_settings_modal_all_categories() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::mocha();
+
+ for cat in SettingsCategory::ALL {
+ let mut state = AppState {
+ show_settings_popup: true,
+ settings_category: cat,
+ settings_selected_row: 0,
+ ..Default::default()
+ };
+
+ terminal
+ .draw(|frame| {
+ let area = frame.area();
+ draw(frame, area, &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let rendered = (0..buffer.area.height)
+ .map(|y| {
+ (0..buffer.area.width)
+ .map(|x| buffer[(x, y)].symbol())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert!(rendered.contains("Settings & Preferences"));
+ assert!(rendered.contains(cat.title()));
+ }
+ }
+
+ #[test]
+ fn test_render_settings_modal_basic_terminal() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::fallback(false);
+ let mut state = AppState {
+ show_settings_popup: true,
+ basic_terminal: true,
+ settings_category: SettingsCategory::General,
+ settings_selected_row: 0,
+ ..Default::default()
+ };
+
+ terminal
+ .draw(|frame| {
+ let area = frame.area();
+ draw(frame, area, &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let rendered = (0..buffer.area.height)
+ .map(|y| {
+ (0..buffer.area.width)
+ .map(|x| buffer[(x, y)].symbol())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert!(rendered.contains("Settings & Preferences"));
+ assert!(rendered.contains("Automatic Updates"));
+ }
+
+ #[test]
+ fn test_render_settings_modal_compact_layout() {
+ let backend = TestBackend::new(60, 20);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::mocha();
+ let mut state = AppState {
+ show_settings_popup: true,
+ settings_category: SettingsCategory::General,
+ settings_selected_row: 0,
+ ..Default::default()
+ };
+
+ terminal
+ .draw(|frame| {
+ let area = frame.area();
+ draw(frame, area, &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let rendered = (0..buffer.area.height)
+ .map(|y| {
+ (0..buffer.area.width)
+ .map(|x| buffer[(x, y)].symbol())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert!(rendered.contains("Settings & Preferences"));
+ assert!(rendered.contains("Automatic Updates"));
+ }
+
+ #[test]
+ fn test_render_content_modes_labels() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::mocha();
+ let mut state = AppState {
+ show_settings_popup: true,
+ settings_category: SettingsCategory::ContentModes,
+ settings_selected_row: 0,
+ ..Default::default()
+ };
+
+ terminal
+ .draw(|frame| {
+ let area = frame.area();
+ draw(frame, area, &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let rendered = (0..buffer.area.height)
+ .map(|y| {
+ (0..buffer.area.width)
+ .map(|x| buffer[(x, y)].symbol())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert!(rendered.contains("Streaming Mode"));
+ assert!(rendered.contains("MovieBox & 4KHDHub streaming catalog"));
+ assert!(rendered.contains("BDIX FTP Mirrors"));
+ assert!(rendered.contains("Local high-speed BDIX optical mirrors for streaming"));
+ assert!(rendered.contains("Live TV Mode"));
+ assert!(rendered.contains("Live IPTV channels and custom M3U playlists"));
+ assert!(rendered.contains("Addon Mode"));
+ }
+
+ #[test]
+ fn test_settings_tab_and_row_hit_testing() {
+ let popup = Rect::new(4, 4, 76, 17);
+ let cat = settings_category_tab_at(popup, 7, popup.y + 1, false, SettingsCategory::General);
+ assert_eq!(cat, Some(SettingsCategory::General));
+ let cat_underline =
+ settings_category_tab_at(popup, 7, popup.y + 2, false, SettingsCategory::General);
+ assert_eq!(cat_underline, Some(SettingsCategory::General));
+
+ let cat_modes =
+ settings_category_tab_at(popup, 19, popup.y + 1, false, SettingsCategory::General);
+ assert_eq!(cat_modes, Some(SettingsCategory::ContentModes));
+
+ let row_rects = settings_row_rects(popup, SettingsCategory::General);
+ assert_eq!(row_rects.len(), 3);
+
+ let clicked_row = settings_row_at(popup, SettingsCategory::General, 40, row_rects[0].y);
+ assert_eq!(clicked_row, Some(0));
+
+ let clicked_subtext =
+ settings_row_at(popup, SettingsCategory::General, 40, row_rects[0].y + 1);
+ assert_eq!(clicked_subtext, Some(0));
+ }
+}
diff --git a/tests/settings_hub.rs b/tests/settings_hub.rs
new file mode 100644
index 0000000..80d97b1
--- /dev/null
+++ b/tests/settings_hub.rs
@@ -0,0 +1,379 @@
+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
+use moviebox_tui::{
+ player::PlayerKind,
+ tui::{
+ action::Action,
+ app::App,
+ commands::{ParsedCommand, SlashCommand},
+ state::{AppState, SettingsCategory, settings_player_label},
+ widgets::settings::{
+ category_tab_rects, settings_category_tab_at, settings_row_at, settings_row_rects,
+ },
+ },
+};
+use ratatui::layout::Rect;
+
+#[test]
+fn test_settings_command_parsing_and_aliases() {
+ let state = AppState::default();
+ assert!(SlashCommand::Settings.is_available(&state));
+ assert_eq!(SlashCommand::Settings.name(), "/settings");
+ assert_eq!(
+ SlashCommand::parse("/settings"),
+ Some(ParsedCommand::Settings)
+ );
+ assert_eq!(SlashCommand::parse("/pref"), Some(ParsedCommand::Settings));
+ assert_eq!(
+ SlashCommand::parse("/preferences"),
+ Some(ParsedCommand::Settings)
+ );
+ assert_eq!(
+ SlashCommand::parse("/options"),
+ Some(ParsedCommand::Settings)
+ );
+ assert_eq!(SlashCommand::parse("/config"), Some(ParsedCommand::Config));
+ assert_eq!(SlashCommand::parse("/help"), Some(ParsedCommand::Help));
+ assert_eq!(SlashCommand::parse("/?"), Some(ParsedCommand::Help));
+
+ let suggestions = SlashCommand::suggest(&state, "/");
+ assert_eq!(
+ suggestions,
+ vec![
+ "/settings".to_string(),
+ "/browse".to_string(),
+ "/history".to_string(),
+ "/favorites".to_string(),
+ "/theme".to_string(),
+ "/clear".to_string(),
+ "/help".to_string(),
+ ]
+ );
+
+ let s_sug = SlashCommand::suggest(&state, "/s");
+ assert_eq!(s_sug, vec!["/settings".to_string()]);
+
+ let c_sug = SlashCommand::suggest(&state, "/c");
+ assert_eq!(c_sug, vec!["/clear".to_string()]);
+
+ let p_sug = SlashCommand::suggest(&state, "/p");
+ assert!(p_sug.is_empty());
+
+ let toggle_suggestions = SlashCommand::suggest(&state, "/toggle");
+ assert!(toggle_suggestions.is_empty());
+}
+
+#[test]
+fn test_settings_modal_has_active_modal() {
+ let mut state = AppState::default();
+ assert!(!state.has_active_modal());
+
+ state.show_settings_popup = true;
+ assert!(state.has_active_modal());
+
+ state.show_settings_popup = false;
+ assert!(!state.has_active_modal());
+}
+
+#[test]
+fn test_settings_toggle_modes_safety_guard() {
+ let mut state = AppState {
+ streaming_enabled: true,
+ tv_enabled: false,
+ addons_enabled: false,
+ ..Default::default()
+ };
+ assert!(!state.can_disable_streaming_mode());
+ assert!(state.can_disable_tv_mode());
+ assert!(state.can_disable_addons_mode());
+
+ state.tv_enabled = true;
+ assert!(state.can_disable_streaming_mode());
+ assert!(state.can_disable_tv_mode());
+}
+
+#[test]
+fn test_settings_player_choices_and_labels() {
+ let mut state = AppState::default();
+ assert_eq!(state.settings_player_choices(), Vec::<&str>::new());
+
+ state.available_players = vec![PlayerKind::Mpv, PlayerKind::Vlc, PlayerKind::Iina];
+ assert_eq!(state.settings_player_choices(), vec!["mpv", "vlc", "iina"]);
+
+ state.default_player = Some("custom_player".to_string());
+ assert_eq!(state.settings_player_choices(), vec!["mpv", "vlc", "iina"]);
+
+ assert_eq!(settings_player_label(None), "None");
+ assert_eq!(settings_player_label(Some("auto")), "None");
+ assert_eq!(settings_player_label(Some("mpv")), "mpv");
+ assert_eq!(settings_player_label(Some("vlc")), "VLC");
+ assert_eq!(settings_player_label(Some("iina")), "IINA");
+ assert_eq!(settings_player_label(Some("android")), "Android Player");
+ assert_eq!(settings_player_label(Some("custom_player")), "Custom");
+}
+
+#[test]
+fn test_settings_player_and_theme_cycling() {
+ let mut state = AppState {
+ available_players: vec![PlayerKind::Mpv, PlayerKind::Vlc],
+ ..Default::default()
+ };
+ assert_eq!(state.default_player, None);
+
+ state.cycle_settings_player(true);
+ assert_eq!(state.default_player, Some("vlc".to_string()));
+
+ state.cycle_settings_player(true);
+ assert_eq!(state.default_player, Some("mpv".to_string()));
+
+ state.cycle_settings_player(false);
+ assert_eq!(state.default_player, Some("vlc".to_string()));
+
+ state.cycle_settings_player(false);
+ assert_eq!(state.default_player, Some("mpv".to_string()));
+
+ let original_theme = state.active_theme_kind.clone();
+ let next_theme = state.cycle_settings_theme(true);
+ assert_ne!(original_theme, next_theme);
+ assert_eq!(state.active_theme_kind, next_theme);
+}
+
+#[tokio::test]
+async fn test_settings_keyboard_navigation_and_actions() {
+ let mut app = App::new();
+
+ app.handle_action(Action::ShowSettingsPopup).await;
+ assert!(app.state().show_settings_popup);
+ assert_eq!(app.state().settings_category, SettingsCategory::General);
+ assert_eq!(app.state().settings_selected_row, 0);
+
+ app.handle_action(Action::Key(KeyEvent::new(
+ KeyCode::Tab,
+ KeyModifiers::empty(),
+ )))
+ .await;
+ assert_eq!(
+ app.state().settings_category,
+ SettingsCategory::ContentModes
+ );
+
+ app.handle_action(Action::Key(KeyEvent::new(
+ KeyCode::BackTab,
+ KeyModifiers::empty(),
+ )))
+ .await;
+ assert_eq!(app.state().settings_category, SettingsCategory::General);
+
+ app.handle_action(Action::Key(KeyEvent::new(
+ KeyCode::Down,
+ KeyModifiers::empty(),
+ )))
+ .await;
+ assert_eq!(app.state().settings_selected_row, 1);
+
+ app.state_mut().available_players = vec![PlayerKind::Mpv, PlayerKind::Vlc];
+ app.state_mut().default_player = None;
+ app.handle_action(Action::SettingsAdjustValue(true)).await;
+ assert_eq!(app.state().default_player, Some("vlc".to_string()));
+
+ app.handle_action(Action::SettingsActivateRow).await;
+ assert!(app.state().player_picker_popup);
+ assert!(app.state().settings_player_picker);
+
+ app.handle_action(Action::MoveDown).await;
+ assert_eq!(app.state().player_picker_state.selected(), Some(0));
+
+ app.handle_action(Action::Submit).await;
+ assert!(!app.state().player_picker_popup);
+ assert!(!app.state().settings_player_picker);
+ assert!(app.state().show_settings_popup);
+ assert_eq!(app.state().default_player, Some("mpv".to_string()));
+ app.handle_action(Action::Key(KeyEvent::new(
+ KeyCode::Esc,
+ KeyModifiers::empty(),
+ )))
+ .await;
+ assert!(!app.state().show_settings_popup);
+}
+
+#[tokio::test]
+async fn test_settings_modes_toggle_keeps_popup_open() {
+ let mut app = App::new();
+ app.state_mut().streaming_enabled = true;
+ app.state_mut().tv_enabled = true;
+ app.state_mut().addons_enabled = true;
+ app.state_mut()
+ .set_mode(moviebox_tui::tui::state::AppMode::Streaming);
+
+ app.handle_action(Action::ShowSettingsPopup).await;
+ assert!(app.state().show_settings_popup);
+
+ app.handle_action(Action::SelectSettingsCategory(
+ SettingsCategory::ContentModes,
+ ))
+ .await;
+ assert!(app.state().show_settings_popup);
+ assert_eq!(
+ app.state().settings_category,
+ SettingsCategory::ContentModes
+ );
+
+ app.state_mut().settings_selected_row = 1;
+ let initial_bdix = app.state().bdix_enabled;
+ app.handle_action(Action::SettingsActivateRow).await;
+ assert!(app.state().show_settings_popup);
+ assert_eq!(app.state().bdix_enabled, !initial_bdix);
+
+ app.handle_action(Action::SettingsAdjustValue(true)).await;
+ assert!(app.state().show_settings_popup);
+ assert_eq!(app.state().bdix_enabled, initial_bdix);
+
+ app.state_mut().settings_selected_row = 2;
+ app.state_mut().tv_enabled = false;
+ app.handle_action(Action::SettingsActivateRow).await;
+ assert!(app.state().show_settings_popup);
+ assert!(app.state().tv_enabled);
+
+ app.state_mut().settings_selected_row = 0;
+ app.state_mut().streaming_enabled = true;
+ app.handle_action(Action::SettingsActivateRow).await;
+ assert!(app.state().show_settings_popup);
+ assert!(!app.state().streaming_enabled);
+ assert!(app.state().is_tv_mode);
+
+ app.handle_action(Action::SettingsActivateRow).await;
+ assert!(app.state().show_settings_popup);
+ app.state_mut().settings_selected_row = 3;
+ app.state_mut().addons_enabled = false;
+ app.handle_action(Action::SettingsActivateRow).await;
+ assert!(app.state().show_settings_popup);
+ assert!(app.state().addons_enabled);
+
+ app.state_mut()
+ .set_mode(moviebox_tui::tui::state::AppMode::Streaming);
+ app.state_mut().streaming_enabled = true;
+ app.state_mut().tv_enabled = true;
+ app.state_mut().addons_enabled = true;
+ app.handle_action(Action::CloseSettingsPopup).await;
+ assert!(!app.state().show_settings_popup);
+}
+
+#[tokio::test]
+async fn test_settings_appearance_theme_cycle_and_popup() {
+ let mut app = App::new();
+ app.handle_action(Action::ShowSettingsPopup).await;
+ assert!(app.state().show_settings_popup);
+
+ app.handle_action(Action::SelectSettingsCategory(SettingsCategory::Appearance))
+ .await;
+ assert!(app.state().show_settings_popup);
+ assert_eq!(app.state().settings_category, SettingsCategory::Appearance);
+
+ let initial_theme = app.state().active_theme_kind.clone();
+ app.handle_action(Action::SettingsAdjustValue(true)).await;
+ assert!(app.state().show_settings_popup);
+ assert!(!app.state().show_theme_popup);
+ assert_ne!(app.state().active_theme_kind, initial_theme);
+
+ app.handle_action(Action::SettingsActivateRow).await;
+ assert!(app.state().show_settings_popup);
+ assert!(app.state().show_theme_popup);
+
+ app.handle_action(Action::Key(KeyEvent::new(
+ KeyCode::Esc,
+ KeyModifiers::empty(),
+ )))
+ .await;
+ assert!(app.state().show_settings_popup);
+ assert!(!app.state().show_theme_popup);
+
+ app.handle_action(Action::CloseSettingsPopup).await;
+ assert!(!app.state().show_settings_popup);
+}
+
+#[tokio::test]
+async fn test_settings_mouse_interaction() {
+ let mut app = App::new();
+ app.handle_action(Action::ShowSettingsPopup).await;
+ assert!(app.state().show_settings_popup);
+
+ app.handle_action(Action::MouseClick(0, 0)).await;
+ assert!(!app.state().show_settings_popup);
+}
+
+#[tokio::test]
+async fn test_settings_mouse_tab_and_row_clicks() {
+ let mut app = App::new();
+ app.handle_action(Action::ShowSettingsPopup).await;
+ assert!(app.state().show_settings_popup);
+ assert_eq!(app.state().settings_category, SettingsCategory::General);
+
+ let popup = Rect::new(4, 4, 76, 17);
+ let cat = settings_category_tab_at(popup, 7, popup.y + 1, false, SettingsCategory::General);
+ assert_eq!(cat, Some(SettingsCategory::General));
+
+ let cat_modes =
+ settings_category_tab_at(popup, 19, popup.y + 1, false, SettingsCategory::General);
+ assert_eq!(cat_modes, Some(SettingsCategory::ContentModes));
+
+ let cat_appearance =
+ settings_category_tab_at(popup, 37, popup.y + 1, false, SettingsCategory::General);
+ assert_eq!(cat_appearance, Some(SettingsCategory::Appearance));
+
+ let cat_maint =
+ settings_category_tab_at(popup, 52, popup.y + 1, false, SettingsCategory::General);
+ assert_eq!(cat_maint, Some(SettingsCategory::StorageInfo));
+
+ let rows = settings_row_rects(popup, SettingsCategory::General);
+ assert_eq!(rows.len(), 3);
+ assert_eq!(
+ settings_row_at(popup, SettingsCategory::General, rows[0].x + 2, rows[0].y),
+ Some(0)
+ );
+ assert_eq!(
+ settings_row_at(
+ popup,
+ SettingsCategory::General,
+ rows[0].x + 2,
+ rows[0].y + 1
+ ),
+ Some(0)
+ );
+ assert_eq!(
+ settings_row_at(popup, SettingsCategory::General, rows[1].x + 2, rows[1].y),
+ Some(1)
+ );
+ assert_eq!(
+ settings_row_at(popup, SettingsCategory::General, rows[2].x + 2, rows[2].y),
+ Some(2)
+ );
+}
+
+#[test]
+fn test_settings_compact_tabs_rects() {
+ let popup = Rect::new(4, 2, 60, 20);
+ let tabs_area = Rect::new(popup.x + 3, popup.y + 1, popup.width - 6, 2);
+ let rects = category_tab_rects(tabs_area, false, SettingsCategory::General);
+ assert!(!rects.is_empty());
+
+ let hit = settings_category_tab_at(
+ popup,
+ rects[0].1.x,
+ popup.y + 1,
+ false,
+ SettingsCategory::General,
+ );
+ assert_eq!(hit, Some(SettingsCategory::General));
+}
+
+#[test]
+fn test_expand_download_path() {
+ assert_eq!(AppState::expand_download_path(""), None);
+ assert_eq!(AppState::expand_download_path("default"), None);
+ assert_eq!(AppState::expand_download_path("reset"), None);
+
+ let path = AppState::expand_download_path("/tmp/moviebox_downloads");
+ assert_eq!(
+ path,
+ Some(std::path::PathBuf::from("/tmp/moviebox_downloads"))
+ );
+}