Skip to content

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

feat: add poster support and item rendering to search results with refactored navigation state

Samir Hossainsd2ad751354bc
diff --git a/src/lib.rs b/src/lib.rs
index 8a76791..edd6b14 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,3 @@
pub mod tui;
-pub mod v3;
+pub mod providers;
diff --git a/src/providers/mod.rs b/src/providers/mod.rs
new file mode 100644
index 0000000..9169905
--- /dev/null
+++ b/src/providers/mod.rs
@@ -0,0 +1 @@
+pub mod moviebox;
diff --git a/src/v3/client.rs b/src/providers/moviebox/client.rs
similarity index 95%
rename from src/v3/client.rs
rename to src/providers/moviebox/client.rs
index 8d084fc..129a972 100644
--- a/src/v3/client.rs
+++ b/src/providers/moviebox/client.rs
@@ -1,4 +1,4 @@
-use crate::v3::crypto::build_signed_headers;
+use crate::providers::moviebox::crypto::build_signed_headers;
use reqwest::Response;
use serde_json::Value;
use std::sync::Arc;
@@ -53,8 +53,8 @@ impl MovieBoxClient {
.build()
.expect("Failed to build reqwest client; TLS backend may be missing");
- let (user_agent, client_info) = crate::v3::crypto::generate_client_info_and_ua();
- let spoofed_ip = crate::v3::crypto::random_spoofed_ip();
+ let (user_agent, client_info) = crate::providers::moviebox::crypto::generate_client_info_and_ua();
+ let spoofed_ip = crate::providers::moviebox::crypto::random_spoofed_ip();
Self {
client,
@@ -66,7 +66,6 @@ impl MovieBoxClient {
}
}
-
pub async fn init(&self) -> Result<(), ScraperError> {
let path = "/wefeed-mobile-bff/tab-operating?page=1&tabId=0&version=";
let _ = self.get(path).await?;
diff --git a/src/v3/crypto.rs b/src/providers/moviebox/crypto.rs
similarity index 85%
rename from src/v3/crypto.rs
rename to src/providers/moviebox/crypto.rs
index c711324..528a904 100644
--- a/src/v3/crypto.rs
+++ b/src/providers/moviebox/crypto.rs
@@ -246,43 +246,3 @@ pub(crate) fn random_spoofed_ip() -> String {
let host: u8 = rng.random_range(1..254);
format!("103.241.224.{}", host)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_generate_x_client_token() {
- let ts = 1629876543210;
- let token = generate_x_client_token(ts);
- assert!(token.starts_with("1629876543210,"));
- let parts: Vec<&str> = token.split(',').collect();
- assert_eq!(parts.len(), 2);
- assert_eq!(parts[1].len(), 32);
- }
-
- #[test]
- fn test_build_canonical_string() {
- let ts = 1000;
- let url = "https://api.example.com/test?b=2&a=1";
- let canonical = build_canonical_string("GET", Some("application/json"), Some("application/json"), url, None, ts);
-
- let parts: Vec<&str> = canonical.split('\n').collect();
- assert_eq!(parts.len(), 7);
- assert_eq!(parts[0], "GET");
- assert_eq!(parts[1], "application/json");
- assert_eq!(parts[2], "application/json");
- assert_eq!(parts[3], "");
- assert_eq!(parts[4], "1000");
- assert_eq!(parts[5], "");
- assert_eq!(parts[6], "/test?a=1&b=2");
- }
-
- #[test]
- fn test_generate_x_tr_signature() {
- let ts = 1000;
- let url = "https://api.example.com/test";
- let sig = generate_x_tr_signature("GET", Some("application/json"), Some("application/json"), url, None, ts);
- assert!(sig.starts_with("1000|2|"));
- }
-}
diff --git a/src/v3/mod.rs b/src/providers/moviebox/mod.rs
similarity index 94%
rename from src/v3/mod.rs
rename to src/providers/moviebox/mod.rs
index 9ae6201..be00a77 100644
--- a/src/v3/mod.rs
+++ b/src/providers/moviebox/mod.rs
@@ -1,12 +1,12 @@
pub mod client;
pub mod crypto;
-use client::{ScraperError, MovieBoxClient};
-use serde_json::{Value, json};
+use client::{MovieBoxClient, ScraperError};
+use serde_json::{json, Value};
impl MovieBoxClient {
pub async fn search(&self, query: &str, page: usize) -> Result<Value, ScraperError> {
- self.search_with_tab(query, page, "All").await
+ self.search_with_tab(query, page, "MovieTV").await
}
pub async fn suggest(&self, query: &str) -> Result<Value, ScraperError> {
@@ -72,7 +72,6 @@ impl MovieBoxClient {
self.get(&path).await
}
-
pub async fn get_all_resources(
&self,
subject_id: &str,
@@ -89,8 +88,10 @@ impl MovieBoxClient {
handles.push(tokio::spawn(async move {
tokio::time::timeout(
std::time::Duration::from_secs(4),
- c.get_resources(&sid, season, episode, 1, Some(&r))
- ).await.unwrap_or(Err(ScraperError::ApiStatus(408)))
+ c.get_resources(&sid, season, episode, 1, Some(&r)),
+ )
+ .await
+ .unwrap_or(Err(ScraperError::ApiStatus(408)))
}));
}
diff --git a/src/tui/action.rs b/src/tui/action.rs
index ad48a08..41b74e7 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -7,8 +7,9 @@ pub enum Action {
SelectLanguage(usize),
ToggleLogs,
ToggleHelp,
- Search(String),
- SearchSuccess(String, serde_json::Value),
+ Search { query: String },
+ SelectSuggestion { query: String },
+ SearchSuccess { query: String, payload: serde_json::Value },
SearchFailure(String),
Suggest(String),
SuggestSuccess(String, serde_json::Value),
@@ -16,6 +17,7 @@ pub enum Action {
MoveDown,
MoveLeft,
MoveRight,
+ ClosePopup,
Submit,
TabPane,
FetchPreview(String),
@@ -40,6 +42,7 @@ pub enum Action {
ResourcesSuccess(serde_json::Value),
ResourcesFailure(String),
PosterSuccess(String, std::sync::Arc<image::DynamicImage>),
+ SearchPosterLoaded(String, Option<std::sync::Arc<image::DynamicImage>>),
Log(String),
UpdateAvailable(String),
}
diff --git a/src/tui/app.rs b/src/tui/app.rs
index fff23fd..d781be2 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -8,7 +8,7 @@ use crate::tui::{
state::{AppState, InputMode, Screen, SearchResult},
theme::Theme,
};
-use crate::v3::client::MovieBoxClient;
+use crate::providers::moviebox::client::MovieBoxClient;
use update_informer::Check;
pub struct App {
@@ -68,10 +68,15 @@ impl App {
}
pub async fn run(&mut self, terminal: &mut DefaultTerminal) -> std::io::Result<()> {
- if self.state.image_picker.is_none() {
- let picker = ratatui_image::picker::Picker::from_query_stdio()
- .unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
- self.state.image_picker = Some(picker);
+ if self.state.image_picker.is_none() && self.state.image_supported {
+ match ratatui_image::picker::Picker::from_query_stdio() {
+ Ok(picker) => {
+ self.state.image_picker = Some(picker);
+ }
+ Err(_) => {
+ self.state.image_supported = false;
+ }
+ }
}
let mut events = EventHandler::new(Duration::from_millis(60));
@@ -196,8 +201,19 @@ impl App {
KeyCode::Enter => {
let query = self.state.search_query.trim().to_string();
if !query.is_empty() {
+ let selected_suggestion = self.state.suggest_index.is_some();
self.state.input_mode = InputMode::Normal;
- self.action_sender.send(Action::Search(query)).ok();
+ self.state.search_suggestions.clear();
+ self.state.suggest_index = None;
+ self.state.search_results.clear();
+ self.state.search_list_state.select(None);
+ self.state.last_search_edit = std::time::Instant::now();
+ let action = if selected_suggestion {
+ Action::SelectSuggestion { query }
+ } else {
+ Action::Search { query }
+ };
+ self.action_sender.send(action).ok();
}
}
KeyCode::Backspace => {
@@ -242,6 +258,12 @@ impl App {
KeyCode::Down => {
self.action_sender.send(Action::MoveDown).ok();
}
+ KeyCode::Left => {
+ self.action_sender.send(Action::MoveLeft).ok();
+ }
+ KeyCode::Right => {
+ self.action_sender.send(Action::MoveRight).ok();
+ }
KeyCode::Enter => {
self.action_sender.send(Action::Submit).ok();
}
@@ -257,6 +279,9 @@ impl App {
{
self.state.input_mode = InputMode::Editing;
self.state.search_query.push(c);
+
+ self.state.search_suggestions.clear();
+ self.state.suggest_index = None;
self.state.status_message = String::new(); self.state.status_timer = 150;
}
_ => {}
@@ -363,7 +388,16 @@ impl App {
self.state.show_logs = !self.state.show_logs;
}
Action::ToggleHelp => {
- self.state.show_help = !self.state.show_help;
+ if matches!(
+ self.state.active_screen,
+ Screen::Home | Screen::Search | Screen::Details
+ ) {
+ self.state.show_help = !self.state.show_help;
+ }
+ }
+
+ Action::ClosePopup => {
+ self.state.active_popup = None;
}
Action::GoBack => {
if self.state.subtitle_popup {
@@ -451,14 +485,29 @@ impl App {
.unwrap_or(&raw_title)
.trim()
.to_string();
+
+ let normalized_query = query.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "");
+ let normalized_title = clean_title.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "");
+ if !normalized_title.contains(&normalized_query) && !normalized_query.is_empty() {
+ continue;
+ }
+
if !self.state.search_suggestions.contains(&clean_title) {
self.state.search_suggestions.push(clean_title);
}
}
}
}
- Action::Search(query) => {
+ Action::SelectSuggestion { query } => {
+ self.action_sender.send(Action::Search { query }).ok();
+ }
+ Action::Search { query } => {
+ self.state.active_screen = Screen::Home;
+ self.state.selected_details = None;
+ self.state.selected_resources = None;
self.state.is_loading = true;
+ self.state.search_results.clear();
+ self.state.search_list_state.select(Some(0));
self.state.search_suggestions.clear();
self.state.suggest_index = None;
self.state.status_message = format!("Searching for '{}'...", query); self.state.status_timer = 150;
@@ -470,7 +519,7 @@ impl App {
tokio::spawn(async move {
match client.search(&query_clone, 1).await {
Ok(res) => {
- sender.send(Action::SearchSuccess(query_clone, res)).ok();
+ sender.send(Action::SearchSuccess { query: query_clone, payload: res }).ok();
}
Err(e) => {
sender.send(Action::SearchFailure(format!("{:?}", e))).ok();
@@ -478,13 +527,13 @@ impl App {
}
});
}
- Action::SearchSuccess(query, payload) => {
+ Action::SearchSuccess { query, payload } => {
if query != self.state.search_query.trim() {
return None;
}
self.state.is_loading = false;
self.state.search_results.clear();
-
+ let _ = std::fs::write("search_debug.json", serde_json::to_string_pretty(&payload).unwrap_or_default());
let mut count = 0;
let subjects_opt = payload
.get("results")
@@ -494,7 +543,6 @@ impl App {
.and_then(|s| s.as_array());
if let Some(subjects) = subjects_opt {
- let query_lower = self.state.search_query.to_lowercase().trim().to_string();
for item in subjects {
let id = item
.get("subjectId")
@@ -514,9 +562,10 @@ impl App {
.trim()
.to_string();
- if !query_lower.is_empty()
- && !clean_title.to_lowercase().contains(&query_lower)
- {
+
+ let normalized_query = query.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "");
+ let normalized_title = raw_title.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "");
+ if !normalized_title.contains(&normalized_query) && !normalized_query.is_empty() {
continue;
}
@@ -530,6 +579,14 @@ impl App {
.unwrap_or("N/A")
.to_string();
+ let cover_url = item.get("poster")
+ .or_else(|| item.get("cover"))
+ .or_else(|| item.get("pic"))
+ .and_then(|c| {
+ c.as_str().or_else(|| c.get("url").and_then(|u| u.as_str()))
+ })
+ .map(|s| s.to_string());
+
let is_duplicate = self.state.search_results.iter().any(|r| {
r.title == clean_title
&& r.release_year == release_year
@@ -542,40 +599,72 @@ impl App {
title: clean_title,
stype,
release_year,
+ cover_url,
});
count += 1;
}
}
+ let query_lower = query.to_lowercase();
self.state.search_results.sort_by(|a, b| {
- b.stype
- .cmp(&a.stype)
+ let a_title = a.title.to_lowercase();
+ let b_title = b.title.to_lowercase();
+
+ let a_exact = a_title == query_lower;
+ let b_exact = b_title == query_lower;
+
+ let a_starts = a_title.starts_with(&query_lower);
+ let b_starts = b_title.starts_with(&query_lower);
+
+ b_exact.cmp(&a_exact)
+ .then_with(|| b_starts.cmp(&a_starts))
+ .then_with(|| b.stype.cmp(&a.stype))
.then_with(|| b.release_year.cmp(&a.release_year))
});
}
+ if !self.state.search_results.is_empty() {
+ let results_to_fetch = self.state.search_results.iter().take(15).map(|r| {
+ (r.id.clone(), r.stype, r.cover_url.clone())
+ }).collect::<Vec<_>>();
+
+ let sender = self.action_sender.clone();
+ tokio::spawn(async move {
+ for (id, stype, cover_url) in results_to_fetch {
+ let mut url_to_fetch = cover_url;
+ if url_to_fetch.is_none() {
+ let type_str = if stype == 2 { "series" } else { "movie" };
+ if let Ok(resp) = reqwest::get(&format!("https://v3-cinemeta.strem.io/meta/{}/{}.json", type_str, id)).await {
+ if let Ok(json) = resp.json::<serde_json::Value>().await {
+ url_to_fetch = json.get("meta").and_then(|m| m.get("poster")).and_then(|p| p.as_str()).map(|s| s.to_string());
+ }
+ }
+ }
+ if let Some(url) = url_to_fetch {
+ if let Ok(resp) = reqwest::get(&url).await {
+ if let Ok(bytes) = resp.bytes().await {
+ if let Ok(img) = image::load_from_memory(&bytes) {
+ let _ = sender.send(Action::SearchPosterLoaded(id, Some(std::sync::Arc::new(img))));
+ }
+ }
+ }
+ }
+ }
+ });
+ }
+
self.state.status_message = format!("Found {} results.", count); self.state.status_timer = 150;
self.state
.add_log(format!("Search completed: {} items loaded.", count));
- let query_lower = query.to_lowercase().trim().to_string();
- let exact_match_idx = self.state.search_results.iter().position(|r| r.title.to_lowercase() == query_lower);
+ self.state.search_list_state.select(Some(0));
+
+ self.state.last_search_edit = std::time::Instant::now();
- if let Some(idx) = exact_match_idx {
- self.state.search_list_state.select(Some(idx));
- self.action_sender.send(Action::Submit).ok();
- } else if count == 1 {
+ if let Some(res) = self.state.search_results.first() {
self.state.search_list_state.select(Some(0));
- self.action_sender.send(Action::Submit).ok();
+ self.action_sender.send(Action::FetchPreview(res.id.clone())).ok();
} else {
- self.state
- .search_list_state
- .select(if count > 0 { Some(0) } else { None });
-
- if let Some(res) = self.state.search_results.first() {
- self.action_sender
- .send(Action::FetchPreview(res.id.clone()))
- .ok();
- }
+ self.state.search_list_state.select(None);
}
}
Action::SearchFailure(err) => {
@@ -738,7 +827,18 @@ impl App {
}
}
Action::MoveLeft => {
- if self.state.active_screen == Screen::Details {
+ if self.state.active_screen == Screen::Home {
+ let current = self.state.search_list_state.selected().unwrap_or(0);
+ let jump = self.state.visible_items.max(1);
+ if current > jump {
+ self.state.search_list_state.select(Some(current - jump));
+ } else {
+ self.state.search_list_state.select(Some(0));
+ }
+ if let Some(res) = self.state.search_results.get(self.state.search_list_state.selected().unwrap_or(0)) {
+ self.action_sender.send(Action::FetchPreview(res.id.clone())).ok();
+ }
+ } else if self.state.active_screen == Screen::Details {
match self.state.details_pane {
crate::tui::state::DetailsPane::Streams => {
if !self.state.available_seasons.is_empty() {
@@ -777,7 +877,19 @@ impl App {
}
}
Action::MoveRight => {
- if self.state.active_screen == Screen::Details {
+ if self.state.active_screen == Screen::Home {
+ let current = self.state.search_list_state.selected().unwrap_or(0);
+ let jump = self.state.visible_items.max(1);
+ let total = self.state.search_results.len();
+ if current + jump < total {
+ self.state.search_list_state.select(Some(current + jump));
+ } else if total > 0 {
+ self.state.search_list_state.select(Some(total - 1));
+ }
+ if let Some(res) = self.state.search_results.get(self.state.search_list_state.selected().unwrap_or(0)) {
+ self.action_sender.send(Action::FetchPreview(res.id.clone())).ok();
+ }
+ } else if self.state.active_screen == Screen::Details {
match self.state.details_pane {
crate::tui::state::DetailsPane::Seasons => {
self.state.details_pane = crate::tui::state::DetailsPane::Episodes;
@@ -808,6 +920,12 @@ impl App {
}
}
Action::Submit => {
+ if self.state.is_loading {
+ return None;
+ }
+ if self.state.last_search_edit.elapsed().as_millis() < 500 {
+ return None;
+ }
if self.state.subtitle_popup {
self.state.subtitle_popup = false;
let idx = self.state.subtitle_list_state.selected().unwrap_or(0);
@@ -853,6 +971,7 @@ impl App {
}
Action::FetchPreview(id) => {
self.state.preview_loading = true;
+ self.state.selected_poster = None;
let client = self.client.clone();
let sender = self.action_sender.clone();
let id_clone = id.clone();
@@ -869,7 +988,7 @@ impl App {
}
Action::PreviewSuccess(id, json) => {
let current_id = if self.state.active_screen == Screen::Details {
- self.state.selected_details.as_ref().and_then(|d| d.get("id")).and_then(|i| i.as_str()).map(|s| s.to_string())
+ self.state.selected_details.as_ref().and_then(|d| d.get("id")).and_then(|i| i.as_i64().map(|n| n.to_string()).or_else(|| i.as_str().map(|s| s.to_string())))
} else {
self.state
.search_list_state
@@ -881,6 +1000,8 @@ impl App {
if current_id.as_deref() != Some(id.as_str()) {
return None;
}
+
+ let _ = std::fs::write("preview_debug.json", serde_json::to_string_pretty(&json).unwrap_or_default());
self.state.preview_loading = false;
self.state.search_preview = Some(json.clone());
@@ -909,21 +1030,22 @@ impl App {
Action::PosterSuccess(id, img) => {
self.state.image_cache.put(id.clone(), img.clone());
- let current_id = if self.state.active_screen == Screen::Details {
- self.state.selected_details.as_ref().and_then(|d| d.get("id")).and_then(|i| i.as_str()).map(|s| s.to_string())
- } else {
- self.state
- .search_list_state
- .selected()
- .and_then(|idx| self.state.search_results.get(idx))
- .map(|res| res.id.clone())
- };
+ let current_id = self.state
+ .search_list_state
+ .selected()
+ .and_then(|idx| self.state.search_results.get(idx))
+ .map(|res| res.id.clone());
if current_id.as_deref() == Some(id.as_str()) {
self.state.poster_image = Some((*img).clone());
self.state.poster_protocol = None;
}
}
+ Action::SearchPosterLoaded(id, img_opt) => {
+ if let Some(img) = img_opt {
+ self.state.search_posters.insert(id, img);
+ }
+ }
Action::PreviewFailure(err) => {
self.state.preview_loading = false;
self.state.add_log(format!("Preview fetch failed: {}", err));
@@ -935,7 +1057,7 @@ impl App {
{
if let Ok(mut clipboard) = arboard::Clipboard::new() {
let _ = clipboard.set_text(link.clone());
- self.state.toast_message = Some("[ ✓ ] Copied stream link!".to_string());
+ self.state.toast_message = Some("✓ Copied stream link!".to_string());
self.state.toast_timer = 30;
self.state.add_log(
"Stream link successfully copied to clipboard.".to_string(),
@@ -949,7 +1071,7 @@ impl App {
if self.state.active_screen == Screen::Details
&& let Some(link) = self.get_selected_link()
{
- self.state.toast_message = Some("[ i ] Fetching subtitles...".to_string());
+ self.state.toast_message = Some("✓ Fetching subtitles...".to_string());
self.state.toast_timer = 40;
let subject_id = self
.state
@@ -997,7 +1119,7 @@ impl App {
}
Action::LaunchMpv(link, subtitle_url) => {
use std::process::{Command, Stdio};
- self.state.toast_message = Some("[ i ] Launching MPV...".to_string());
+ self.state.toast_message = Some("✓ Launching MPV...".to_string());
self.state.toast_timer = 40;
let mut cmd = Command::new("mpv");
@@ -1012,7 +1134,7 @@ impl App {
if cmd.spawn().is_ok() {
self.state.add_log("MPV started successfully.".to_string());
} else {
- self.state.toast_message = Some("[ ! ] Error: mpv player not found in PATH".to_string());
+ self.state.toast_message = Some("✗ Error: mpv player not found in PATH".to_string());
self.state.toast_timer = 60;
self.state.add_log("Error starting mpv process. Command failed.".to_string());
}
@@ -1045,7 +1167,7 @@ impl App {
if let Some(link) = link_opt {
self.state.toast_message =
- Some("[ ↓ ] Starting native download...".to_string());
+ Some("✓ Starting native download...".to_string());
self.state.toast_timer = 40;
self.state.download_status = Some("Connecting...".to_string());
self.state.download_progress = Some(0.0);
@@ -1518,9 +1640,10 @@ impl App {
if let Some(dubs) = payload.get("dubs").and_then(|d| d.as_array()) {
let mut current_idx = 0;
- let current_id = payload.get("id").and_then(|i| i.as_str()).unwrap_or("");
+ let current_id = payload.get("id").and_then(|i| i.as_i64().map(|n| n.to_string()).or_else(|| i.as_str().map(|s| s.to_string()))).unwrap_or_default();
for (i, dub) in dubs.iter().enumerate() {
- if dub.get("subjectId").and_then(|i| i.as_str()) == Some(current_id) {
+ let dub_id = dub.get("subjectId").and_then(|i| i.as_i64().map(|n| n.to_string()).or_else(|| i.as_str().map(|s| s.to_string())));
+ if dub_id == Some(current_id.clone()) {
current_idx = i;
}
}
@@ -1631,7 +1754,7 @@ impl App {
.cancel_download
.store(true, std::sync::atomic::Ordering::SeqCst);
self.state.download_status = Some("Cancelling...".to_string());
- self.state.toast_message = Some("[ ! ] Cancelling download...".to_string());
+ self.state.toast_message = Some("✗ Cancelling download...".to_string());
self.state.toast_timer = 40;
}
Action::Log(msg) => {
@@ -1698,26 +1821,23 @@ impl App {
if let Some(msg) = &self.state.toast_message {
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::style::{Color, Style};
- use ratatui::widgets::{Block, Borders, Paragraph};
+ use ratatui::widgets::Paragraph;
let chunks = Layout::default()
.direction(Direction::Vertical)
- .constraints([Constraint::Min(0), Constraint::Length(3)])
+ .constraints([Constraint::Min(0), Constraint::Length(1)])
.split(area);
- let h_chunks = Layout::default()
+ let toast_area = Layout::default()
.direction(Direction::Horizontal)
- .constraints([Constraint::Percentage(70), Constraint::Percentage(30)])
- .split(chunks[0]);
+ .constraints([Constraint::Min(0), Constraint::Length(msg.chars().count() as u16 + 2)])
+ .split(chunks[1])[1];
- let toast_area = Layout::default()
- .direction(Direction::Vertical)
- .constraints([Constraint::Min(0), Constraint::Length(3)])
- .split(h_chunks[1])[1];
+
+ let color = if self.state.toast_timer < 10 { self.theme.muted } else { self.theme.success };
let p = Paragraph::new(msg.clone())
- .block(Block::default().borders(Borders::ALL))
- .style(Style::default().fg(Color::Green));
+ .style(color.add_modifier(ratatui::style::Modifier::BOLD));
frame.render_widget(p, toast_area);
}
}
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index 763d823..0f94770 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -3,7 +3,7 @@ use ratatui::{
Frame,
layout::{Alignment, Constraint, Direction, Layout, Rect},
text::{Line, Span},
- widgets::{Block, Borders, Cell, Paragraph, Row, Table, Wrap},
+ widgets::{Block, Borders, List, ListItem, Paragraph, Wrap},
};
pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme) {
@@ -13,6 +13,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
Constraint::Length(14),
Constraint::Length(1),
Constraint::Min(10),
+ Constraint::Length(1),
])
.split(area);
let bottom_area = chunks[2];
@@ -85,7 +86,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.and_then(|c| c.as_str())
.filter(|s| !s.is_empty())
.unwrap_or("N/A");
- let content_rating = details_json
+ let _content_rating = details_json
.get("contentRating")
.and_then(|c| c.as_str())
.filter(|s| !s.is_empty())
@@ -110,30 +111,25 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let inner_area = details_block.inner(chunks[0]);
frame.render_widget(details_block.clone(), chunks[0]);
- let poster_width = (inner_area.height as f32 * 2.2).ceil() as u16;
+ let poster_width = (inner_area.height as f32 * 1.33).ceil() as u16;
let h_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Length(poster_width),
- Constraint::Length(1),
+ Constraint::Length(2),
Constraint::Min(1),
])
.split(inner_area);
- let poster_area = h_chunks[0];
+ let poster_height = ((poster_width as f32) / 1.33).ceil() as u16;
+ let poster_area = ratatui::layout::Rect {
+ height: h_chunks[0].height.min(poster_height),
+ ..h_chunks[0]
+ };
let right_area = h_chunks[2];
- let right_chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(10),
- Constraint::Min(1),
- ])
- .split(right_area);
- let meta_area = right_chunks[0];
- let synopsis_area = right_chunks[1];
if let Some(img) = &state.poster_image {
if state.poster_protocol.as_ref().map(|(r, _)| *r) != Some(poster_area)
@@ -158,92 +154,83 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
frames[(state.tick_count as usize) % frames.len()]
};
- let placeholder = Paragraph::new(format!("\n\n\n\n\n {} Loading Art...", current_spinner))
+ let placeholder_block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(theme.muted);
+
+ let inner = placeholder_block.inner(poster_area);
+
+ let (pad, msg) = if state.is_loading {
+ let p = "\n".repeat((inner.height.saturating_sub(1) / 2) as usize);
+ (p, format!("{}\nLoading Art", current_spinner))
+ } else {
+ let p = "\n".repeat((inner.height.saturating_sub(1) / 2) as usize);
+ (p, title.to_string())
+ };
+
+ let placeholder = Paragraph::new(format!("{}{}", pad, msg))
.style(theme.text_dim)
- .alignment(Alignment::Center);
+ .alignment(Alignment::Center)
+ .wrap(Wrap { trim: true })
+ .block(placeholder_block);
frame.render_widget(placeholder, poster_area);
}
- let mut staff_list = Vec::new();
- if let Some(staff) = details_json.get("staffList").and_then(|s| s.as_array()) {
- for person in staff.iter().take(3) {
- if let Some(name) = person.get("name").and_then(|n| n.as_str()) {
- staff_list.push(name.to_string());
- }
- }
- }
- let cast = if staff_list.is_empty() {
- "N/A".to_string()
- } else {
- staff_list.join(", ")
- };
+ let num_rating = imdb_rating.parse::<f32>().unwrap_or(0.0);
- let mut dubs_list = Vec::new();
- if let Some(dubs) = details_json.get("dubs").and_then(|d| d.as_array()) {
- for dub in dubs {
- if let Some(lang) = dub.get("lanName").and_then(|n| n.as_str()) {
- let mut name = if lang.to_lowercase().starts_with("original") {
- "Original".to_string()
- } else {
- lang.replace("dub", "")
- .replace("Dub", "")
- .trim()
- .to_string()
- };
- if name.to_lowercase() == "ptbr" {
- name = "Portuguese (BR)".to_string();
- }
- if !dubs_list.contains(&name) {
- dubs_list.push(name);
- }
- }
- }
- }
+ let filled_stars = (num_rating / 2.0).round() as usize;
+ let filled_stars = filled_stars.clamp(0, 5);
+ let empty_stars = 5 - filled_stars;
+ let stars_str = format!("{}{}", "★".repeat(filled_stars), "☆".repeat(empty_stars));
- dubs_list.sort_by(|a, b| {
- if a == "Original" {
- std::cmp::Ordering::Less
- } else if b == "Original" {
- std::cmp::Ordering::Greater
- } else {
- a.cmp(b)
- }
- });
- let dubbing_str = if dubs_list.is_empty() {
- "N/A".to_string()
+ let title_line = Line::from(vec![
+ Span::styled(format!("{}", title), theme.text.add_modifier(ratatui::style::Modifier::BOLD)),
+ ]);
+
+ let rating_line = Line::from(vec![
+ Span::styled(format!("{} {} IMDb", stars_str, imdb_rating), theme.rating),
+ ]);
+
+ let duration_str = if duration.is_empty() || duration == "N/A" {
+ "".to_string()
} else {
- dubs_list.join(", ")
+ format!(" │ {}", duration)
};
- let viewers = details_json
- .get("viewers")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let label_style = theme.header;
- let val_style = theme.text;
-
- let meta_rows = vec![
- Row::new(vec![Cell::from("Title:").style(label_style), Cell::from(title).style(val_style)]),
- Row::new(vec![Cell::from("Type:").style(label_style), Cell::from(type_str).style(val_style)]),
- Row::new(vec![Cell::from("Genre:").style(label_style), Cell::from(genres).style(val_style)]),
- Row::new(vec![Cell::from("Released:").style(label_style), Cell::from(year).style(val_style)]),
- Row::new(vec![Cell::from("Duration:").style(label_style), Cell::from(duration).style(val_style)]),
- Row::new(vec![Cell::from("Rating:").style(label_style), Cell::from(format!("{} (IMDb: {})", content_rating, imdb_rating)).style(val_style)]),
- Row::new(vec![Cell::from("Country:").style(label_style), Cell::from(country).style(val_style)]),
- Row::new(vec![Cell::from("Cast:").style(label_style), Cell::from(cast).style(val_style)]),
- Row::new(vec![Cell::from("Dubbing:").style(label_style), Cell::from(dubbing_str).style(val_style)]),
- Row::new(vec![Cell::from("Viewers:").style(label_style), Cell::from(viewers.to_string()).style(val_style)]),
+ let meta_line = Line::from(vec![
+ Span::styled(format!("{} • {} • {}{}", type_str, year, country, duration_str), theme.text),
+ ]);
+
+ let genre_line = Line::from(vec![
+ Span::styled(genres.to_string(), theme.text_dim),
+ ]);
+
+
+ let top_meta = vec![
+ title_line,
+ rating_line,
+ meta_line,
+ genre_line,
];
+
+
+ let meta_chunks = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([
+ Constraint::Length(5),
+ Constraint::Min(1),
+ ])
+ .split(right_area);
- let meta_table = Table::new(meta_rows, [Constraint::Length(10), Constraint::Min(10)]);
- frame.render_widget(meta_table, meta_area);
+ let meta_p = Paragraph::new(top_meta);
+ frame.render_widget(meta_p, meta_chunks[0]);
let syn_lines = vec![
- Line::from(vec![Span::styled("Synopsis: ", label_style), Span::styled(intro, theme.text_dim)])
+ Line::from(vec![Span::styled("Synopsis", theme.title)]),
+ Line::from(vec![Span::styled(intro, theme.text_dim.add_modifier(ratatui::style::Modifier::DIM))])
];
let intro_p = Paragraph::new(syn_lines).wrap(Wrap { trim: true });
- frame.render_widget(intro_p, synopsis_area);
+ frame.render_widget(intro_p, meta_chunks[1]);
let has_languages = if let Some(dubs) = details_json.get("dubs").and_then(|d| d.as_array()) {
dubs.len() > 1
@@ -328,11 +315,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
Block::default()
.borders(Borders::ALL)
.border_type(ratatui::widgets::BorderType::Rounded)
- .title(" Audio/Dub ")
+ .title(" Audio ")
.border_style(lang_border),
)
- .highlight_style(theme.highlight.bg(ratatui::style::Color::Rgb(30, 30, 50)))
- .highlight_symbol(">> ");
+ .highlight_style(theme.highlight)
+ .highlight_symbol("▌ ");
let lang_area = if !state.language_chosen {
let v_split = Layout::default()
@@ -376,8 +363,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.title(" Seasons ")
.border_style(seasons_border),
)
- .highlight_style(theme.highlight.bg(ratatui::style::Color::Rgb(30, 30, 50)))
- .highlight_symbol(">> ");
+ .highlight_style(theme.highlight)
+ .highlight_symbol("▌ ");
let seasons_area = if has_languages {
left_panel_chunks[1]
@@ -411,8 +398,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.title(" Episodes ")
.border_style(eps_border),
)
- .highlight_style(theme.highlight.bg(ratatui::style::Color::Rgb(30, 30, 50)))
- .highlight_symbol(">> ");
+ .highlight_style(theme.highlight)
+ .highlight_symbol("▌ ");
let eps_area = if has_languages {
left_panel_chunks[2]
@@ -433,85 +420,94 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
theme.border
};
+ let mut streams_count = 0;
+ if let Some(res) = &state.selected_resources {
+ if let Some(list) = res.get("list").and_then(|l| l.as_array()) {
+ streams_count = list.len();
+ }
+ }
+
+ let streams_title = if streams_count > 0 {
+ format!(" Streams • {} Available ", streams_count)
+ } else {
+ " Streams ".to_string()
+ };
+
let streams_block = Block::default()
.borders(Borders::ALL)
.border_type(ratatui::widgets::BorderType::Rounded)
- .title(ratatui::text::Line::from(" Streams ").alignment(Alignment::Left))
- .title(ratatui::text::Line::from(" [Enter/P] Play [D] Download [C] Copy Link [B/Esc] Back ").alignment(Alignment::Right))
+ .title(ratatui::text::Line::from(streams_title).alignment(Alignment::Left))
.title_style(theme.title)
.border_style(streams_border);
- let mut render_table = None;
+ let mut render_list = None;
match &state.selected_resources {
Some(res) => {
if let Some(list) = res.get("list").and_then(|l| l.as_array()) {
- let rows: Vec<Row> = list
+ let mut prev_quality = String::new();
+ let selected_idx = state.resource_list_state.selected();
+
+ let list_items: Vec<ListItem> = list
.iter()
- .map(|file| {
- let resolution =
- file.get("resolution").and_then(|r| r.as_i64()).unwrap_or(0);
- let codec = file
- .get("codecName")
- .and_then(|c| c.as_str())
- .unwrap_or("None");
- let upload_by = file
- .get("uploadBy")
- .and_then(|u| u.as_str())
- .unwrap_or("None");
+ .enumerate()
+ .map(|(i, file)| {
+ let resolution = file.get("resolution").and_then(|r| r.as_i64()).unwrap_or(0);
+ let quality_str = format!("{}p", resolution);
+
+ let is_first_of_quality = quality_str != prev_quality;
+ prev_quality = quality_str.clone();
+
+ let codec = file.get("codecName").and_then(|c| c.as_str()).unwrap_or("None");
+ let _upload_by = file.get("uploadBy").and_then(|u| u.as_str()).unwrap_or("None");
let size_str = file.get("size").and_then(|s| s.as_str()).unwrap_or("0");
+
let size_formatted = if let Ok(bytes) = size_str.parse::<f64>() {
let mb = bytes / 1024.0 / 1024.0;
if mb > 1024.0 {
- format!("{:.1} GB", mb / 1024.0)
+ format!("{:.1}GB", mb / 1024.0)
} else {
- format!("{:.0} MB", mb)
+ format!("{:.0}MB", mb)
}
} else {
"Unknown".to_string()
};
- let subs_count = file
- .get("extCaptions")
- .and_then(|c| c.as_array())
- .map(|a| a.len())
- .unwrap_or(0);
- let subs_str = if subs_count > 0 {
- format!("{} subs", subs_count)
+ let is_selected = Some(i) == selected_idx;
+ let pointer = if is_selected { "▌ " } else { " " };
+
+ let stream_style = if is_selected {
+ theme.highlight.clone()
} else {
- "None".to_string()
+ theme.text_dim.clone()
};
-
- Row::new(vec![
- Cell::from(format!("{}p", resolution)).style(theme.header),
- Cell::from(codec).style(theme.text),
- Cell::from(size_formatted).style(theme.text_dim),
- Cell::from(subs_str).style(if subs_count > 0 {
- theme.border_focus
- } else {
- theme.text_dim
- }),
- Cell::from(upload_by).style(theme.text),
- ])
+
+
+
+ let stream_line = ratatui::text::Line::from(vec![
+ ratatui::text::Span::styled(pointer, theme.accent),
+ ratatui::text::Span::styled(format!("{:<7} {:<6} ", size_formatted, codec), stream_style),
+ ]);
+
+ let mut lines = vec![];
+ if is_first_of_quality {
+ if i > 0 {
+ lines.push(ratatui::text::Line::from(""));
+ }
+ lines.push(ratatui::text::Line::from(ratatui::text::Span::styled(
+ quality_str,
+ theme.accent
+ )));
+ }
+
+ lines.push(stream_line);
+ ListItem::new(lines)
})
.collect();
- let widths = [
- Constraint::Length(6),
- Constraint::Length(6),
- Constraint::Length(9),
- Constraint::Length(8),
- Constraint::Min(15),
- ];
-
- let t = Table::new(rows, widths)
- .header(
- Row::new(vec!["Res", "Codec", "Size", "Subs", "Uploader"])
- .style(theme.title),
- )
- .block(streams_block)
- .row_highlight_style(theme.highlight.bg(ratatui::style::Color::Rgb(30, 30, 50)))
- .highlight_symbol(">> ");
- render_table = Some(t);
+ let l = List::new(list_items)
+ .block(streams_block.clone())
+ .highlight_symbol("");
+ render_list = Some(l);
} else {
let has_multiple_dubs = state
.selected_details
@@ -530,7 +526,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let p = Paragraph::new(format!("{}{}", pad, msg))
.style(theme.text_dim)
.alignment(Alignment::Center)
- .block(streams_block);
+ .block(streams_block.clone());
frame.render_widget(p, streams_area);
}
}
@@ -567,13 +563,15 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let p = Paragraph::new(format!("{}{}", pad, msg))
.style(style)
.alignment(Alignment::Center)
- .block(streams_block);
+ .block(streams_block.clone());
frame.render_widget(p, streams_area);
}
}
- if let Some(t) = render_table {
- frame.render_stateful_widget(t, streams_area, &mut state.resource_list_state);
+ if let Some(l) = render_list {
+ frame.render_stateful_widget(l, streams_area, &mut state.resource_list_state);
+ } else {
+ frame.render_widget(streams_block, streams_area);
}
}
@@ -607,8 +605,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.border_style(theme.border),
)
.highlight_style(theme.highlight)
- .highlight_symbol(">> ");
+ .highlight_symbol("▌ ");
frame.render_stateful_widget(list, popup_area, &mut state.subtitle_list_state);
}
+
+ let footer_text = "Enter Play D Download C Copy Link Esc Back";
+ let footer_p = Paragraph::new(footer_text)
+ .alignment(Alignment::Center)
+ .style(theme.muted);
+ frame.render_widget(footer_p, chunks[3]);
}
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 028ab00..1886e55 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -5,7 +5,7 @@ use crate::tui::{
use ratatui::{
Frame,
layout::{Alignment, Constraint, Direction, Layout, Rect},
- widgets::{Block, BorderType, Borders, Cell, Paragraph, Row, Table},
+ widgets::{Block, Cell, Paragraph, Row, Table},
};
pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme) {
@@ -68,7 +68,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
&& !state.status_message.to_lowercase().contains("fail")
{
if state.tick_count < 1 {
- return; // terminal opens black
+ return;
}
let is_narrow = area.width < 60;
@@ -125,9 +125,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.split(vertical_chunks[2]);
let logo_style = if state.tick_count == 1 {
- ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(60, 60, 60))
+ ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(49, 50, 68))
} else if state.tick_count == 2 {
- ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(140, 140, 140))
+ ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(108, 112, 134))
} else {
theme.title
};
@@ -139,9 +139,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
frame.render_widget(title_art, horizontal_chunks[1]);
let version_style = if state.tick_count == 1 {
- ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(40, 40, 40))
+ ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(49, 50, 68))
} else if state.tick_count == 2 {
- ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(90, 90, 90))
+ ratatui::style::Style::default().fg(ratatui::style::Color::Rgb(108, 112, 134))
} else {
theme.text_dim
};
@@ -184,16 +184,10 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
}
} else {
- let desired_height = if state.is_loading {
- 10
- } else {
- std::cmp::max(state.search_results.len() as u16 + 4, 6)
- };
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3),
- Constraint::Length(desired_height),
Constraint::Min(0),
])
.split(area);
@@ -207,12 +201,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
});
frame.render_widget(search_bar, search_bar_area);
- let list_block = Block::default()
- .borders(Borders::ALL)
- .border_type(BorderType::Rounded)
- .title(" Results ")
- .title_style(theme.title)
- .border_style(theme.border);
+ let list_block = Block::default();
if state.is_loading {
let spinner = if state.basic_terminal {
@@ -240,38 +229,171 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.style(theme.text_dim);
frame.render_widget(p, v_chunks[1]);
} else if !state.search_results.is_empty() {
+
+ let selected_idx = state.search_list_state.selected();
+ let offset = state.search_list_state.offset();
+
+
+ let row_height = 3;
+ state.visible_items = (chunks[1].height as usize) / (row_height as usize);
let rows: Vec<Row> = state
.search_results
.iter()
- .map(|res| {
- let type_tag = if res.stype == 1 {
- "MOVIE"
- } else if res.stype == 2 {
- "TV"
- } else {
- "OTHER"
- };
- Row::new(vec![
- Cell::from(type_tag).style(theme.header),
- Cell::from(res.title.as_str()).style(theme.text),
- Cell::from(res.release_year.as_str()).style(theme.text_dim),
- ])
- })
+ .map(|_| Row::new(vec![Cell::from("")]).height(row_height))
.collect();
- let widths = [
- Constraint::Length(8),
- Constraint::Percentage(70),
- Constraint::Length(10),
- ];
-
- let table = Table::new(rows, widths)
- .header(Row::new(vec!["Type", "Title", "Date"]).style(theme.title))
- .block(list_block)
- .row_highlight_style(theme.highlight.bg(ratatui::style::Color::Rgb(30, 30, 50)))
- .highlight_symbol(">> ");
+ let table = Table::new(rows, [Constraint::Percentage(100)])
+ .block(list_block);
frame.render_stateful_widget(table, chunks[1], &mut state.search_list_state);
+
+ let mut inner_area = chunks[1];
+ inner_area.x += 1;
+ inner_area.y += 1;
+ inner_area.width = inner_area.width.saturating_sub(2);
+ inner_area.height = inner_area.height.saturating_sub(2);
+
+ let mut current_y = inner_area.y;
+
+ for (i, res) in state.search_results.iter().enumerate().skip(offset) {
+ if current_y >= inner_area.y + inner_area.height {
+ break;
+ }
+
+ let item_area = Rect {
+ x: inner_area.x,
+ y: current_y,
+ width: inner_area.width,
+ height: 3.min(inner_area.y + inner_area.height.saturating_sub(current_y)),
+ };
+
+ if item_area.height == 0 { break; }
+
+ let is_selected = Some(i) == selected_idx;
+
+ let layout = Layout::default()
+ .direction(Direction::Horizontal)
+ .constraints([
+ Constraint::Length(2),
+ Constraint::Length(4),
+ Constraint::Length(1),
+ Constraint::Min(0),
+ ])
+ .split(item_area);
+
+ let highlight_area = layout[0];
+ let poster_area = layout[1];
+ let text_area = layout[3];
+
+ if is_selected {
+ let indicator = Paragraph::new(ratatui::text::Line::from(vec![
+ ratatui::text::Span::styled("▌ ", theme.accent.clone())
+ ]));
+ frame.render_widget(indicator, highlight_area);
+ }
+
+ let mut poster_rendered = false;
+ if let Some(img) = state.search_posters.get(&res.id) {
+ if state.image_supported {
+ let needs_protocol = state.search_poster_protocols.get(&res.id).map(|(r, _)| *r) != Some(poster_area);
+ if needs_protocol {
+ if let Some(picker) = &mut state.image_picker {
+ let size = ratatui::layout::Size::new(poster_area.width, poster_area.height.min(3));
+ if let Ok(proto) = picker.new_protocol((**img).clone(), size, ratatui_image::Resize::Fit(None)) {
+ state.search_poster_protocols.insert(res.id.clone(), (poster_area, proto));
+ }
+ }
+ }
+ if let Some((_, proto)) = state.search_poster_protocols.get(&res.id) {
+ let p_area = Rect { height: poster_area.height.min(3), ..poster_area };
+ frame.render_widget(ratatui_image::Image::new(proto), p_area);
+ poster_rendered = true;
+ }
+ }
+ }
+
+ if !poster_rendered {
+ let p = Paragraph::new("████\n████\n████")
+ .style(theme.muted);
+ let p_area = Rect { height: poster_area.height.min(3), ..poster_area };
+ frame.render_widget(p, p_area);
+ }
+
+ let text_layout = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Min(0),
+ ])
+ .split(text_area);
+
+ let title_style = if is_selected { theme.title } else { theme.text };
+ let max_title_width = text_area.width.saturating_sub(4) as usize;
+ let mut display_title = res.title.clone();
+ if display_title.chars().count() > max_title_width && max_title_width > 3 {
+ display_title = display_title.chars().take(max_title_width - 3).collect::<String>();
+ display_title.push_str("...");
+ }
+
+ let type_tag = if res.stype == 1 { "Movie" } else if res.stype == 2 { "TV Series" } else { "Other" };
+
+ let title_line = ratatui::text::Line::from(vec![
+ ratatui::text::Span::styled(display_title, title_style),
+ ]);
+ if text_layout[0].height > 0 {
+ frame.render_widget(Paragraph::new(title_line), text_layout[0]);
+ }
+
+ let mut info_spans = vec![];
+
+ if is_selected {
+ if state.preview_loading || state.is_loading {
+ info_spans.push(ratatui::text::Span::styled(&res.release_year, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ info_spans.push(ratatui::text::Span::styled(type_tag, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ info_spans.push(ratatui::text::Span::styled("Loading...", theme.text_dim));
+ } else if let Some(meta) = &state.search_preview {
+ let rating = meta.get("imdbRating").or_else(|| meta.get("imdbRatingValue")).and_then(|v| v.as_str());
+ if let Some(r) = rating {
+ info_spans.push(ratatui::text::Span::styled("★ ", theme.rating.clone()));
+ info_spans.push(ratatui::text::Span::styled(r, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ }
+ info_spans.push(ratatui::text::Span::styled(&res.release_year, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+
+ let mut g_names = vec![];
+ if let Some(genres) = meta.get("genres").and_then(|g| g.as_array()) {
+ g_names = genres.iter()
+ .filter_map(|g| g.get("name").and_then(|n| n.as_str()).map(|s| s.to_string()))
+ .collect();
+ }
+ if !g_names.is_empty() {
+ info_spans.push(ratatui::text::Span::styled(g_names.join(" • "), theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ }
+ info_spans.push(ratatui::text::Span::styled(type_tag, theme.text));
+ } else {
+ info_spans.push(ratatui::text::Span::styled(&res.release_year, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ info_spans.push(ratatui::text::Span::styled(type_tag, theme.text));
+ }
+ } else {
+ info_spans.push(ratatui::text::Span::styled(&res.release_year, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ info_spans.push(ratatui::text::Span::styled(type_tag, theme.text));
+ }
+
+ if text_layout[1].height > 0 && !info_spans.is_empty() {
+ frame.render_widget(Paragraph::new(ratatui::text::Line::from(info_spans)), text_layout[1]);
+ }
+
+ current_y += row_height;
+
+ }
+
} else {
let inner_area = list_block.inner(chunks[1]);
frame.render_widget(list_block, chunks[1]);
@@ -319,7 +441,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if dropdown_area.y + dropdown_area.height <= area.height || search_area.y > area.height / 2 {
frame.render_widget(ratatui::widgets::Clear, dropdown_area);
let items: Vec<ratatui::widgets::ListItem> = state.search_suggestions.iter().enumerate().map(|(i, s)| {
- let text = if Some(i) == state.suggest_index { format!(">> {}", s) } else { format!(" {}", s) };
+ let text = if Some(i) == state.suggest_index { format!("▌ {}", s) } else { format!(" {}", s) };
let style = if Some(i) == state.suggest_index { theme.highlight } else { theme.text };
ratatui::widgets::ListItem::new(ratatui::text::Line::from(ratatui::text::Span::styled(text, style)).alignment(ratatui::layout::Alignment::Left))
}).collect();
diff --git a/src/tui/screens/logs.rs b/src/tui/screens/logs.rs
index ebe8b32..240baa8 100644
--- a/src/tui/screens/logs.rs
+++ b/src/tui/screens/logs.rs
@@ -24,7 +24,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
])
.split(popup_layout[1])[1];
- frame.render_widget(Clear, popup_area); // Clear background under popup
+ frame.render_widget(Clear, popup_area);
let list_items: Vec<ListItem> = state
.logs
diff --git a/src/tui/state.rs b/src/tui/state.rs
index b377272..e576ef6 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -28,6 +28,7 @@ pub struct SearchResult {
pub title: String,
pub stype: i64,
pub release_year: String,
+ pub cover_url: Option<String>,
}
pub struct AppState {
@@ -39,11 +40,16 @@ pub struct AppState {
pub search_suggestions: Vec<String>,
pub suggest_index: Option<usize>,
pub search_results: Vec<SearchResult>,
+ pub search_posters: std::collections::HashMap<String, std::sync::Arc<image::DynamicImage>>,
+ pub search_poster_protocols: std::collections::HashMap<String, (ratatui::layout::Rect, ratatui_image::protocol::Protocol)>,
pub search_list_state: TableState,
pub selected_details: Option<serde_json::Value>,
pub selected_resources: Option<serde_json::Value>,
- pub resource_list_state: TableState,
+ pub active_popup: Option<String>,
+ pub selected_poster: Option<std::sync::Arc<image::DynamicImage>>,
+ pub selected_poster_protocol: Option<(ratatui::layout::Rect, ratatui_image::protocol::Protocol)>,
+ pub resource_list_state: ListState,
pub details_pane: DetailsPane,
pub selected_season: usize,
@@ -60,10 +66,12 @@ pub struct AppState {
pub poster_image: Option<image::DynamicImage>,
pub poster_protocol: Option<(ratatui::layout::Rect, ratatui_image::protocol::Protocol)>,
pub image_picker: Option<ratatui_image::picker::Picker>,
+ pub image_supported: bool,
pub image_cache: lru::LruCache<String, std::sync::Arc<image::DynamicImage>>,
pub show_logs: bool,
pub show_help: bool,
+ pub visible_items: usize,
pub logs: Vec<String>,
pub logs_scroll: usize,
@@ -99,11 +107,16 @@ impl Default for AppState {
search_suggestions: Vec::new(),
suggest_index: None,
search_results: Vec::new(),
+ search_posters: std::collections::HashMap::new(),
+ search_poster_protocols: std::collections::HashMap::new(),
search_list_state: TableState::default(),
basic_terminal: std::env::var("TERM_PROGRAM").unwrap_or_default() == "Apple_Terminal",
selected_details: None,
selected_resources: None,
- resource_list_state: TableState::default(),
+ active_popup: None,
+ selected_poster: None,
+ selected_poster_protocol: None,
+ resource_list_state: ListState::default(),
details_pane: DetailsPane::default(),
selected_season: 1,
@@ -119,9 +132,11 @@ impl Default for AppState {
poster_image: None,
poster_protocol: None,
image_picker: None,
+ image_supported: true,
image_cache: lru::LruCache::new(std::num::NonZeroUsize::new(10).unwrap()),
show_logs: false,
show_help: false,
+ visible_items: 10,
logs: vec!["MovieBox-Tui started.".to_string()],
logs_scroll: 0,
active_error: None,
diff --git a/src/tui/theme.rs b/src/tui/theme.rs
index 6d4bd70..82fe603 100644
--- a/src/tui/theme.rs
+++ b/src/tui/theme.rs
@@ -13,6 +13,9 @@ pub struct Theme {
pub success: Style,
pub shortcut: Style,
pub overlay: Style,
+ pub rating: Style,
+ pub accent: Style,
+ pub muted: Style,
}
impl Default for Theme {
@@ -26,7 +29,6 @@ impl Default for Theme {
.fg(Color::Rgb(203, 166, 247))
.add_modifier(Modifier::BOLD),
highlight: Style::default()
- .bg(Color::Rgb(49, 50, 68))
.fg(Color::Rgb(137, 180, 250))
.add_modifier(Modifier::BOLD),
header: Style::default()
@@ -36,6 +38,9 @@ impl Default for Theme {
success: Style::default().fg(Color::Rgb(166, 227, 161)),
shortcut: Style::default().fg(Color::Rgb(250, 179, 135)),
overlay: Style::default().fg(Color::Rgb(108, 112, 134)),
+ rating: Style::default().fg(Color::Rgb(249, 226, 175)), // Yellow
+ accent: Style::default().fg(Color::Rgb(137, 220, 235)).add_modifier(Modifier::BOLD), // Sky
+ muted: Style::default().fg(Color::Rgb(88, 91, 112)), // Surface 1
}
}
}