Skip to content

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

fix(tui): accurate clicks, smoother lifecycle, and leaner poster pipeline

Samir Hossains4a3fc0748183
diff --git a/src/tui/action.rs b/src/tui/action.rs
index 8e0c29b..db1fe89 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -59,6 +59,9 @@ pub enum Action {
MoveDown,
MoveLeft,
MoveRight,
+ WheelScroll {
+ up: bool,
+ },
Submit,
TabPane,
BackTabPane,
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 94f0dc5..2fb449d 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -375,14 +375,7 @@ impl App {
let clicked_relative_row = row.saturating_sub(results_y);
let clicked_idx = (clicked_relative_row / row_height) as usize;
- let table_offset = self.state.search_list_state.selected().unwrap_or(0);
- let visible_items =
- ((area.height.saturating_sub(results_y)) / row_height).max(1) as usize;
- let page_start = if table_offset >= visible_items {
- table_offset.saturating_sub(visible_items - 1)
- } else {
- 0
- };
+ let page_start = self.state.search_list_state.offset();
let target_idx = page_start + clicked_idx;
if target_idx < self.state.search_results.len() {
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index d953443..7da8973 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -885,10 +885,13 @@ impl App {
Action::SearchPosterLoaded(id, img_opt) => {
self.state.in_flight_posters.remove(&id);
if let Some(img) = img_opt {
- self.state.image_cache.put(id.clone(), img.clone());
- self.state.search_posters.put(id, img);
+ let cached = crate::service::downscale_for_cache(&img);
+ self.state
+ .image_cache
+ .put(id.clone(), std::sync::Arc::clone(&cached));
+ self.state.search_posters.put(id, cached);
} else {
- self.state.failed_posters.put(id, ());
+ self.state.failed_posters.put(id, std::time::Instant::now());
}
}
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index 0ef0848..a1a061e 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -1,6 +1,10 @@
use super::App;
use crate::providers::models::ProviderKind;
-use crate::tui::{action::Action, event::EventHandler, state::Screen};
+use crate::tui::{
+ action::Action,
+ event::EventHandler,
+ state::{InputMode, Screen},
+};
use ratatui::Frame;
use std::time::Duration;
@@ -14,7 +18,15 @@ impl App {
{
if self.state.image_picker.is_none() && self.state.image_supported {
let picker = if crate::tui::terminal::should_query_images() {
- ratatui_image::picker::Picker::from_query_stdio().ok()
+ tokio::task::spawn_blocking(|| {
+ let options = ratatui_image::picker::cap_parser::QueryStdioOptions {
+ timeout: Duration::from_millis(400),
+ ..Default::default()
+ };
+ ratatui_image::picker::Picker::from_query_stdio_with_options(options).ok()
+ })
+ .await
+ .unwrap_or_default()
} else {
None
};
@@ -139,6 +151,25 @@ impl App {
self.handle_mouse(col, row);
}
+ Action::WheelScroll { up } => {
+ let steps = if self.state.active_screen == Screen::Home
+ && !self.state.favorites_focus
+ && !self.state.search_results.is_empty()
+ && self.state.input_mode != InputMode::Editing
+ {
+ (self.state.poster_rows.max(3) + 1).min(8)
+ } else {
+ 2
+ };
+ let step = if up { Action::MoveUp } else { Action::MoveDown };
+ for _ in 0..steps {
+ let action = step.clone();
+ if let Some(quit) = self.handle_navigation(action).await {
+ return Some(quit);
+ }
+ }
+ }
+
Action::Tick
| Action::FocusChange
| Action::Resize(..)
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index 9ac97c0..bcb0f65 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -1074,7 +1074,7 @@ impl App {
let mut to_fetch = Vec::new();
for (id, cover_url, provider) in results {
- if self.state.search_posters.contains(&id) || self.state.failed_posters.contains(&id) {
+ if self.state.search_posters.contains(&id) || self.state.failed_poster_recently(&id) {
continue;
}
if !self.state.in_flight_posters.insert(id.clone()) {
@@ -1089,9 +1089,10 @@ impl App {
let sender = self.action_sender.clone();
let service = self.service.clone();
+ let semaphore = self.state.poster_fetch_semaphore.clone();
tokio::spawn(async move {
- let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(4));
+ let sem = semaphore;
for (id, cover_url, provider) in to_fetch {
let permit = sem.clone().acquire_owned().await.ok();
let tx = sender.clone();
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 6e28585..7251bb4 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -1,12 +1,17 @@
use super::App;
-use crate::tui::{action::Action, overlay::NotificationKind, state::Screen};
+use crate::tui::{
+ action::Action,
+ overlay::NotificationKind,
+ state::{InputMode, Screen},
+};
impl App {
pub(super) async fn handle_system(&mut self, action: Action) -> Option<()> {
match action {
Action::Tick => {
let mut needs_redraw = (self.state.is_loading && self.state.tick_count % 5 == 0)
- || self.state.tick_count < 15;
+ || self.state.tick_count < 15
+ || self.state.input_mode == InputMode::Editing;
self.state.tick_count = self.state.tick_count.wrapping_add(1);
if !self.state.notifications.is_empty() {
needs_redraw = true;
@@ -109,7 +114,6 @@ impl App {
self.state.last_resize_time = Some((std::time::Instant::now(), w, h));
self.state.poster_protocol = None;
self.state.search_poster_protocols.clear();
- self.state.clear_terminal_before_draw = true;
self.state.dirty = true;
}
diff --git a/src/tui/event.rs b/src/tui/event.rs
index 1bb2bf9..4204d0c 100644
--- a/src/tui/event.rs
+++ b/src/tui/event.rs
@@ -43,10 +43,14 @@ impl EventHandler {
Ok(CrosstermEvent::Mouse(mouse)) => {
match mouse.kind {
crossterm::event::MouseEventKind::ScrollUp => {
- let _ = event_sender.send(Action::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Up, crossterm::event::KeyModifiers::empty()))).await;
+ let _ = event_sender
+ .send(Action::WheelScroll { up: true })
+ .await;
}
crossterm::event::MouseEventKind::ScrollDown => {
- let _ = event_sender.send(Action::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Down, crossterm::event::KeyModifiers::empty()))).await;
+ let _ = event_sender
+ .send(Action::WheelScroll { up: false })
+ .await;
}
crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
let _ = event_sender.send(Action::MouseClick(mouse.column, mouse.row)).await;
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index caa12e3..59eef53 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -630,7 +630,19 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let list_block = Block::default();
if !state.search_results.is_empty() {
let poster_width = if state.image_supported {
- state.poster_rows.saturating_mul(4).div_ceil(3).max(6)
+ state
+ .image_picker
+ .as_ref()
+ .map(|picker| {
+ let font = picker.font_size();
+ let pixel_height =
+ u64::from(state.poster_rows.max(3)) * u64::from(font.height.max(1));
+ let pixel_width = pixel_height * 2 / 3;
+ u16::try_from(pixel_width.div_ceil(u64::from(font.width.max(1))))
+ .unwrap_or(u16::MAX)
+ .max(6)
+ })
+ .unwrap_or_else(|| state.poster_rows.saturating_mul(4).div_ceil(3).max(6))
} else {
12
};
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 5a032bf..588bc2c 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -54,9 +54,10 @@ pub struct AppState {
pub current_tab_id: String,
pub current_page: usize,
pub search_posters: lru::LruCache<String, std::sync::Arc<image::DynamicImage>>,
- pub failed_posters: lru::LruCache<String, ()>,
+ pub failed_posters: lru::LruCache<String, std::time::Instant>,
pub search_poster_protocols:
lru::LruCache<String, ((u16, u16), ratatui_image::protocol::Protocol)>,
+ pub poster_fetch_semaphore: std::sync::Arc<tokio::sync::Semaphore>,
pub in_flight_posters: std::collections::HashSet<String>,
pub search_list_state: TableState,
@@ -204,9 +205,10 @@ impl Default for AppState {
is_homepage_mode: false,
current_tab_id: String::new(),
current_page: 1,
- search_posters: lru::LruCache::new(cache_capacity(300)),
+ search_posters: lru::LruCache::new(cache_capacity(96)),
failed_posters: lru::LruCache::new(cache_capacity(300)),
- search_poster_protocols: lru::LruCache::new(cache_capacity(300)),
+ search_poster_protocols: lru::LruCache::new(cache_capacity(128)),
+ poster_fetch_semaphore: std::sync::Arc::new(tokio::sync::Semaphore::new(4)),
in_flight_posters: std::collections::HashSet::new(),
search_list_state: TableState::default(),
basic_terminal: crate::tui::terminal::uses_basic_ui(),
@@ -397,6 +399,21 @@ impl AppState {
self.status_timer = timer;
}
+ 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,
+ Some(_) => {
+ self.failed_posters.pop(id);
+ false
+ }
+ None => false,
+ }
+ }
+
pub fn clear_search_state(&mut self) {
self.search_query.clear();
self.search_results.clear();
diff --git a/src/tui/theme.rs b/src/tui/theme.rs
index 762b126..aaeb5ca 100644
--- a/src/tui/theme.rs
+++ b/src/tui/theme.rs
@@ -224,14 +224,14 @@ impl Theme {
let has_no_color = std::env::var("NO_COLOR").is_ok();
let is_light = crate::tui::terminal::background_is_light();
- if let Ok(theme_env) = std::env::var("MOVIEBOX_THEME") {
- return Self::from_kind(ThemeKind::parse(&theme_env));
- }
-
if has_no_color {
return Self::monochrome(is_light);
}
+ if let Ok(theme_env) = std::env::var("MOVIEBOX_THEME") {
+ return Self::from_kind(ThemeKind::parse(&theme_env));
+ }
+
let truecolor = colorterm == "truecolor"
|| colorterm == "24bit"
|| term.contains("truecolor")
@@ -259,15 +259,52 @@ impl Theme {
Self::fallback(is_light)
} else if has_256 {
if is_light {
- Self::latte()
+ Self::latte().quantized_to_256()
} else {
- Self::mocha()
+ Self::mocha().quantized_to_256()
}
} else {
Self::fallback(is_light)
}
}
+ /// Maps every RGB color in the theme to the nearest xterm-256 palette
+ /// entry so strict 256-color terminals never receive RGB sequences.
+ pub fn quantized_to_256(mut self) -> Self {
+ self.border = quantize_style(self.border);
+ self.border_focus = quantize_style(self.border_focus);
+ self.text = quantize_style(self.text);
+ self.text_dim = quantize_style(self.text_dim);
+ self.title = quantize_style(self.title);
+ self.highlight = quantize_style(self.highlight);
+ self.header = quantize_style(self.header);
+ self.error = quantize_style(self.error);
+ self.success = quantize_style(self.success);
+ self.shortcut = quantize_style(self.shortcut);
+ self.overlay = quantize_style(self.overlay);
+ self.rating = quantize_style(self.rating);
+ self.accent = quantize_style(self.accent);
+ self.muted = quantize_style(self.muted);
+ self.teal = quantize_style(self.teal);
+ self.lavender = quantize_style(self.lavender);
+ self.sapphire = quantize_style(self.sapphire);
+ self.subtext1 = quantize_style(self.subtext1);
+ self.base = to_indexed_256(self.base);
+ self.bg = quantize_style(self.bg);
+ self.rosewater = quantize_style(self.rosewater);
+ self.flamingo = quantize_style(self.flamingo);
+ self.maroon = quantize_style(self.maroon);
+ self.surface0 = quantize_style(self.surface0);
+ self.surface1 = quantize_style(self.surface1);
+ self.surface2 = quantize_style(self.surface2);
+ self.overlay0 = quantize_style(self.overlay0);
+ self.overlay1 = quantize_style(self.overlay1);
+ self.overlay2 = quantize_style(self.overlay2);
+ self.mantle = quantize_style(self.mantle);
+ self.crust = quantize_style(self.crust);
+ self
+ }
+
pub fn monochrome(is_light: bool) -> Self {
let foreground = if is_light { Color::Black } else { Color::White };
let dim = if is_light {
@@ -680,3 +717,125 @@ impl Theme {
fn cp(r: u8, g: u8, b: u8) -> Color {
Color::Rgb(r, g, b)
}
+
+fn quantize_style(style: Style) -> Style {
+ let mut quantized = style;
+ if let Some(fg) = style.fg {
+ quantized.fg = Some(to_indexed_256(fg));
+ }
+ if let Some(bg) = style.bg {
+ quantized.bg = Some(to_indexed_256(bg));
+ }
+ quantized
+}
+
+fn to_indexed_256(color: Color) -> Color {
+ match color {
+ Color::Rgb(red, green, blue) => Color::Indexed(rgb_to_xterm256(red, green, blue)),
+ other => other,
+ }
+}
+
+const CUBE_LEVELS: [u16; 6] = [0, 95, 135, 175, 215, 255];
+
+fn rgb_to_xterm256(red: u8, green: u8, blue: u8) -> u8 {
+ if red == green && green == blue {
+ if red < 8 {
+ return 16;
+ }
+ if red > 248 {
+ return 231;
+ }
+ return 232 + ((u16::from(red) - 8) / 10) as u8;
+ }
+ let nearest = |channel: u8| -> u16 {
+ let channel = u16::from(channel);
+ let mut best_index = 0_u16;
+ let mut best_distance = u16::MAX;
+ for (index, &level) in CUBE_LEVELS.iter().enumerate() {
+ let distance = channel.abs_diff(level);
+ if distance < best_distance {
+ best_distance = distance;
+ best_index = index as u16;
+ }
+ }
+ best_index
+ };
+ (16 + 36 * nearest(red) + 6 * nearest(green) + nearest(blue)) as u8
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn grayscale_maps_to_gray_ramp() {
+ assert_eq!(rgb_to_xterm256(0, 0, 0), 16);
+ assert_eq!(rgb_to_xterm256(255, 255, 255), 231);
+ assert_eq!(rgb_to_xterm256(128, 128, 128), 232 + 12);
+ }
+
+ #[test]
+ fn pure_colors_map_to_cube() {
+ assert_eq!(rgb_to_xterm256(255, 0, 0), 196);
+ assert_eq!(rgb_to_xterm256(0, 255, 0), 46);
+ assert_eq!(rgb_to_xterm256(0, 0, 255), 21);
+ }
+
+ #[test]
+ fn non_rgb_colors_pass_through() {
+ assert_eq!(to_indexed_256(Color::Red), Color::Red);
+ assert_eq!(to_indexed_256(Color::Indexed(42)), Color::Indexed(42));
+ assert_eq!(to_indexed_256(Color::Rgb(255, 0, 0)), Color::Indexed(196));
+ }
+
+ #[test]
+ fn quantized_mocha_contains_no_rgb() {
+ let quantized = Theme::mocha().quantized_to_256();
+ for style in [
+ quantized.border,
+ quantized.text,
+ quantized.accent,
+ quantized.bg,
+ quantized.lavender,
+ ] {
+ assert!(
+ style
+ .fg
+ .map(|c| !matches!(c, Color::Rgb(..)))
+ .unwrap_or(true)
+ );
+ assert!(
+ style
+ .bg
+ .map(|c| !matches!(c, Color::Rgb(..)))
+ .unwrap_or(true)
+ );
+ }
+ }
+
+ #[test]
+ fn quantized_latte_contains_no_rgb() {
+ let quantized = Theme::latte().quantized_to_256();
+ assert!(
+ quantized
+ .border
+ .fg
+ .map(|c| !matches!(c, Color::Rgb(..)))
+ .unwrap_or(true)
+ );
+ assert!(
+ quantized
+ .bg
+ .fg
+ .map(|c| !matches!(c, Color::Rgb(..)))
+ .unwrap_or(true)
+ );
+ }
+
+ #[test]
+ fn monochrome_dark_uses_light_foreground() {
+ let mono = Theme::monochrome(false);
+ assert_eq!(mono.text.fg, Some(Color::White));
+ }
+}
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index 5fb7658..6642138 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -118,18 +118,45 @@ async fn test_mouse_click_search_input_mode() {
#[tokio::test]
async fn test_mouse_scroll_maps_to_key_actions() {
let mut app = App::new();
- let up_key = crossterm::event::KeyEvent::new(
- crossterm::event::KeyCode::Up,
- crossterm::event::KeyModifiers::empty(),
- );
- let down_key = crossterm::event::KeyEvent::new(
- crossterm::event::KeyCode::Down,
- crossterm::event::KeyModifiers::empty(),
+ app.state_mut().active_screen = Screen::Home;
+ for i in 0..40 {
+ app.state_mut().search_results.push(SearchResult {
+ id: i.to_string(),
+ title: format!("Title {i}"),
+ stype: 1,
+ release_year: "2010".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: ProviderKind::MovieBox,
+ });
+ }
+ app.state_mut().search_list_state.select(Some(20));
+
+ app.handle_action(Action::WheelScroll { up: true }).await;
+ let after_up = app
+ .state()
+ .search_list_state
+ .selected()
+ .expect("selection stays set");
+ assert!(
+ after_up < 20,
+ "wheel up moves the result selection upward (got {after_up})"
);
- app.handle_action(Action::Key(down_key)).await;
- app.handle_action(Action::Key(up_key)).await;
- assert_eq!(app.state().search_query, "");
+ for _ in 0..3 {
+ app.handle_action(Action::WheelScroll { up: false }).await;
+ }
+ let after_down = app
+ .state()
+ .search_list_state
+ .selected()
+ .expect("selection stays set");
+ assert!(
+ after_down > after_up,
+ "wheel down moves the result selection downward"
+ );
+ assert!(after_down < 40, "selection stays within bounds");
}
#[tokio::test]