Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
feat(tui): salvage graphics detection, protocol overrides, and re-probe
Samir Hossainsa4e4b48d6f7e
diff --git a/src/main.rs b/src/main.rsindex c8c1c37..5661540 100644--- a/src/main.rs+++ b/src/main.rs@@ -80,6 +80,10 @@ async fn main() -> std::io::Result<()> {println!(" MOVIEBOX_IINA_PATH Custom iina-cli binary path");println!(" MOVIEBOX_FOURKHDHUB_URL Custom 4KHDHub base URL");println!(" MOVIEBOX_NO_IMAGE Disable poster image queries (1/true)");+ println!(+ " MOVIEBOX_IMAGE_PROTOCOL Force graphics protocol (kitty, sixel, iterm2, none)"+ );+ println!(" MOVIEBOX_CELL_SIZE Override terminal cell size as WxH (e.g. 10x20)");return Ok(());}if argsdiff --git a/src/tui/action.rs b/src/tui/action.rsindex db1fe89..6bdae3b 100644--- a/src/tui/action.rs+++ b/src/tui/action.rs@@ -62,6 +62,7 @@ pub enum Action {WheelScroll {up: bool,},+ ProbeTerminal,Submit,TabPane,BackTabPane,diff --git a/src/tui/app/run.rs b/src/tui/app/run.rsindex eddd826..d415e34 100644--- a/src/tui/app/run.rs+++ b/src/tui/app/run.rs@@ -8,6 +8,11 @@ use crate::tui::{use ratatui::Frame;use std::time::Duration;+enum ForcedProtocol {+ None,+ Type(ratatui_image::picker::ProtocolType),+}+impl App {pub async fn run<B: ratatui::backend::Backend>(&mut self,@@ -17,55 +22,7 @@ impl App {std::io::Error: From<<B as ratatui::backend::Backend>::Error>,{if self.state.image_picker.is_none() && self.state.image_supported {- let picker = if crate::tui::terminal::should_query_images() {- tokio::task::spawn_blocking(|| {- let options = ratatui_image::picker::cap_parser::QueryStdioOptions {- timeout: Duration::from_millis(400),- terminal_background_color_osc: true,- ..Default::default()- };- ratatui_image::picker::Picker::from_query_stdio_with_options(options).ok()- })- .await- .unwrap_or_default()- } else {- None- };- if self.state.theme_is_auto- && let Some(background) = picker.as_ref().and_then(|p| {- p.capabilities()- .iter()- .find_map(|capability| match capability {- ratatui_image::picker::Capability::Background(red, green, blue) => {- Some((*red, *green, *blue))- }- _ => None,- })- })- {- let luminance = 0.2126 * f32::from(background.0)- + 0.7152 * f32::from(background.1)- + 0.0722 * f32::from(background.2);- let is_light = luminance > 128.0;- self.theme = crate::tui::theme::Theme::detect_with_light(Some(is_light));- self.state.active_theme_kind = if is_light { "Latte" } else { "Mocha" }.to_string();- }- if let Some(picker) = picker- && !matches!(- picker.protocol_type(),- ratatui_image::picker::ProtocolType::Halfblocks- )- {- let cell_h = picker.font_size().height;- if cell_h > 0 {- self.state.poster_rows = (96_u16.div_ceil(cell_h)).max(3);- }- self.state.image_picker = Some(picker);- self.state.image_supported = true;- } else {- self.state.image_supported = false;- self.state.image_picker = None;- }+ self.probe_terminal().await;}let mut events = EventHandler::new(Duration::from_millis(100));@@ -152,6 +109,161 @@ impl App {}}+ pub(super) async fn probe_terminal(&mut self) {+ use ratatui_image::picker::{Capability, ProtocolType};++ self.state.image_probe_attempts = self.state.image_probe_attempts.saturating_add(1);+ self.state.last_image_probe = Some(std::time::Instant::now());++ match Self::forced_protocol() {+ Some(ForcedProtocol::None) => {+ self.state.image_supported = false;+ self.state.image_picker = None;+ self.state.initial_probe_failed = false;+ return;+ }+ forced => {+ if forced.is_some() {+ let font_size = Self::cell_size_override().unwrap_or(ratatui_image::FontSize {+ width: 10,+ height: 20,+ });+ #[allow(deprecated)]+ let mut picker = ratatui_image::picker::Picker::from_fontsize(font_size);+ if let Some(ForcedProtocol::Type(protocol)) = forced {+ picker.set_protocol_type(protocol);+ }+ self.accept_picker(picker);+ return;+ }+ }+ }++ let picker = self.query_picker().await;++ if self.state.theme_is_auto+ && let Some(background) = picker.as_ref().and_then(|p| {+ p.capabilities()+ .iter()+ .find_map(|capability| match capability {+ Capability::Background(red, green, blue) => Some((*red, *green, *blue)),+ _ => None,+ })+ })+ {+ let luminance = 0.2126 * f32::from(background.0)+ + 0.7152 * f32::from(background.1)+ + 0.0722 * f32::from(background.2);+ let is_light = luminance > 128.0;+ self.theme = crate::tui::theme::Theme::detect_with_light(Some(is_light));+ self.state.active_theme_kind = if is_light { "Latte" } else { "Mocha" }.to_string();+ }++ let mut picker = match (picker, Self::cell_size_override()) {+ (Some(picker), None) => picker,+ (probed, cell_size) => {+ let font_size = cell_size.unwrap_or(ratatui_image::FontSize {+ width: 10,+ height: 20,+ });+ #[allow(deprecated)]+ let mut rebuilt = ratatui_image::picker::Picker::from_fontsize(font_size);+ if let Some(probed) = probed {+ rebuilt.set_protocol_type(probed.protocol_type());+ }+ if let Some(ForcedProtocol::Type(protocol)) = Self::forced_protocol() {+ rebuilt.set_protocol_type(protocol);+ }+ rebuilt+ }+ };++ let capabilities_empty = picker.capabilities().is_empty();+ if matches!(picker.protocol_type(), ProtocolType::Halfblocks) && !capabilities_empty {+ let caps = picker.capabilities();+ let salvaged = if caps.iter().any(|c| matches!(c, Capability::Kitty)) {+ Some(ProtocolType::Kitty)+ } else if caps.iter().any(|c| matches!(c, Capability::Sixel)) {+ Some(ProtocolType::Sixel)+ } else {+ None+ };+ if let Some(protocol) = salvaged {+ log::info!(+ "salvaging graphics-capable terminal that answered as halfblocks: {:?}",+ protocol+ );+ picker.set_protocol_type(protocol);+ }+ }++ if matches!(picker.protocol_type(), ProtocolType::Halfblocks) {+ self.state.image_supported = false;+ self.state.image_picker = None;+ self.state.initial_probe_failed = !capabilities_empty;+ return;+ }+ self.accept_picker(picker);+ }++ fn accept_picker(&mut self, picker: ratatui_image::picker::Picker) {+ let cell_h = picker.font_size().height;+ if cell_h > 0 {+ self.state.poster_rows = (96_u16.div_ceil(cell_h)).max(3);+ }+ self.state.image_picker = Some(picker);+ self.state.image_supported = true;+ self.state.initial_probe_failed = false;+ }++ async fn query_picker(&self) -> Option<ratatui_image::picker::Picker> {+ if !crate::tui::terminal::should_query_images() {+ return None;+ }+ tokio::task::spawn_blocking(|| {+ let options = ratatui_image::picker::cap_parser::QueryStdioOptions {+ timeout: Duration::from_millis(400),+ terminal_background_color_osc: true,+ ..Default::default()+ };+ ratatui_image::picker::Picker::from_query_stdio_with_options(options).ok()+ })+ .await+ .unwrap_or_default()+ }++ fn forced_protocol() -> Option<ForcedProtocol> {+ match std::env::var("MOVIEBOX_IMAGE_PROTOCOL")+ .unwrap_or_default()+ .to_ascii_lowercase()+ .as_str()+ {+ "none" | "off" | "false" => Some(ForcedProtocol::None),+ "sixel" => Some(ForcedProtocol::Type(+ ratatui_image::picker::ProtocolType::Sixel,+ )),+ "kitty" => Some(ForcedProtocol::Type(+ ratatui_image::picker::ProtocolType::Kitty,+ )),+ "iterm2" => Some(ForcedProtocol::Type(+ ratatui_image::picker::ProtocolType::Iterm2,+ )),+ _ => None,+ }+ }++ fn cell_size_override() -> Option<ratatui_image::FontSize> {+ let raw = std::env::var("MOVIEBOX_CELL_SIZE").ok()?;+ let raw = raw.trim().to_ascii_lowercase();+ let (width, height) = raw.split_once(['x', '*'])?;+ let width: u16 = width.trim().parse().ok()?;+ let height: u16 = height.trim().parse().ok()?;+ if width == 0 || height == 0 {+ return None;+ }+ Some(ratatui_image::FontSize { width, height })+ }+pub async fn handle_action(&mut self, action: Action) -> Option<()> {if self.state.last_resize_time.is_some()|| !matches!(action, Action::Tick | Action::UpdateDownload(..))@@ -171,6 +283,26 @@ impl App {self.handle_mouse(col, row);}+ Action::ProbeTerminal => {+ self.probe_terminal().await;+ let outcome = if self.state.image_supported {+ let protocol = self+ .state+ .image_picker+ .as_ref()+ .map(|picker| format!("{:?}", picker.protocol_type()))+ .unwrap_or_default();+ format!("Graphics protocol: {protocol}")+ } else {+ "No graphics protocol detected; using text placeholders".to_string()+ };+ self.state.notify(+ crate::tui::overlay::NotificationKind::Info,+ "Terminal probe",+ outcome,+ );+ }+Action::WheelScroll { up } => {let steps = if self.state.active_screen == Screen::Home&& !self.state.favorites_focusdiff --git a/src/tui/app/search.rs b/src/tui/app/search.rsindex bcb0f65..df6d838 100644--- a/src/tui/app/search.rs+++ b/src/tui/app/search.rs@@ -140,6 +140,12 @@ impl App {self.state.input_mode = InputMode::Normal;Some(true)}+ crate::tui::commands::ParsedCommand::Probe => {+ self.state.search_query.clear();+ self.state.input_mode = InputMode::Normal;+ self.action_sender.send(Action::ProbeTerminal).ok();+ Some(true)+ }crate::tui::commands::ParsedCommand::Update => {self.state.search_query.clear();self.state.input_mode = InputMode::Normal;diff --git a/src/tui/app/system.rs b/src/tui/app/system.rsindex ccf7fe9..c5c7b71 100644--- a/src/tui/app/system.rs+++ b/src/tui/app/system.rs@@ -107,6 +107,15 @@ impl App {}Action::FocusChange => {+ if self.state.initial_probe_failed+ && self.state.image_probe_attempts < 3+ && self+ .state+ .last_image_probe+ .is_none_or(|probe| probe.elapsed() >= std::time::Duration::from_secs(30))+ {+ self.probe_terminal().await;+ }self.prepare_image_soft_refresh();}@@ -321,8 +330,6 @@ impl App {Action::SelectTheme(theme_name) => {if theme_name.is_empty() && self.state.theme_is_auto {- // Esc from the picker with no explicit theme configured:- // restore the auto-detected theme instead of forcing Mocha.self.theme = crate::tui::theme::Theme::detect();} else {let kind = crate::tui::theme::ThemeKind::parse(&theme_name);diff --git a/src/tui/commands.rs b/src/tui/commands.rsindex 74af652..e7e7d23 100644--- a/src/tui/commands.rs+++ b/src/tui/commands.rs@@ -21,6 +21,7 @@ pub enum SlashCommand {DisableTv,EnableAddons,DisableAddons,+ Probe,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -44,10 +45,11 @@ pub enum ParsedCommand<'a> {DisableTv,EnableAddons,DisableAddons,+ Probe,}impl SlashCommand {- pub const ALL: [Self; 19] = [+ pub const ALL: [Self; 20] = [Self::Browse,Self::History,Self::Favorites,@@ -67,6 +69,7 @@ impl SlashCommand {Self::DisableTv,Self::EnableAddons,Self::DisableAddons,+ Self::Probe,];pub fn name(self) -> &'static str {@@ -90,6 +93,7 @@ impl SlashCommand {Self::DisableTv => "/disable-tv",Self::EnableAddons => "/enable-addons",Self::DisableAddons => "/disable-addons",+ Self::Probe => "/probe",}}@@ -120,6 +124,7 @@ impl SlashCommand {Self::DisableTv => "Disable TV mode navigation",Self::EnableAddons => "Enable Addon mode navigation",Self::DisableAddons => "Disable Addon mode navigation",+ Self::Probe => "Re-detect terminal graphics support",}}@@ -162,7 +167,8 @@ impl SlashCommand {| Self::Update| Self::ToggleUpdate| Self::ClearCache- | Self::Github => true,+ | Self::Github+ | Self::Probe => true,}}@@ -243,6 +249,7 @@ impl SlashCommand {"/disable-tv" => Some(ParsedCommand::DisableTv),"/enable-addons" => Some(ParsedCommand::EnableAddons),"/disable-addons" => Some(ParsedCommand::DisableAddons),+ "/probe" => Some(ParsedCommand::Probe),_ => None,}}diff --git a/src/tui/state.rs b/src/tui/state.rsindex 34c8fd0..15f6a6f 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -94,6 +94,9 @@ pub struct AppState {pub show_theme_popup: bool,pub active_theme_kind: String,pub theme_is_auto: bool,+ pub image_probe_attempts: u8,+ pub last_image_probe: Option<std::time::Instant>,+ pub initial_probe_failed: bool,pub original_theme_kind: Option<String>,pub theme_list_state: ListState,pub show_browse_popup: bool,@@ -243,6 +246,9 @@ impl Default for AppState {poster_image: None,active_theme_kind: String::new(),theme_is_auto: true,+ image_probe_attempts: 0,+ last_image_probe: None,+ initial_probe_failed: false,original_theme_kind: None,show_theme_popup: false,theme_list_state: ListState::default(),diff --git a/src/tui/theme.rs b/src/tui/theme.rsindex d8e41c8..bb73f86 100644--- a/src/tui/theme.rs+++ b/src/tui/theme.rs@@ -256,17 +256,10 @@ impl Theme {}impl Theme {- /// Detects the best theme for the current terminal.- ///- /// Explicit user choices (`MOVIEBOX_THEME` / saved config) are resolved by- /// the caller and take precedence; this path only runs when no explicit- /// choice exists.pub fn detect() -> Self {Self::detect_with_light(None)}- /// Like [`Theme::detect`] but overrides the light/dark decision (for- /// example from an OSC 11 background-color query).pub fn detect_with_light(light: Option<bool>) -> Self {let resolved_light = light.unwrap_or_else(crate::tui::terminal::background_is_light);if std::env::var("NO_COLOR").is_ok() {@@ -302,8 +295,6 @@ impl Theme {}}- /// 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);