use crate::api::Api; use anyhow::{Context, Result, bail}; use image::{DynamicImage, ImageReader, Rgba}; use ratatui_image::protocol::{ImageSource, StatefulProtocol, sixel::StatefulSixel}; use std::{ collections::VecDeque, io::{Cursor, Read, Write}, sync::{ Arc, mpsc::{self, Receiver, Sender}, }, time::{Duration, Instant}, }; #[derive(Default)] pub struct Artwork { pub enabled: bool, pub protocol: Option, pub message: String, pub title: String, target: Option, image_size: Option<(u32, u32)>, font_size: (u16, u16), background: [u8; 4], cache: VecDeque<(String, DynamicImage)>, tx: Option>, rx: Option)>>, } impl Artwork { /// Coalesce playback changes on a dedicated worker so covers cannot block music requests. pub fn new(api: Arc, font_size: (u16, u16)) -> Self { let (tx, jobs) = mpsc::channel::(); let (results, rx) = mpsc::channel(); std::thread::spawn(move || { while let Ok(mut id) = jobs.recv() { for newer in jobs.try_iter() { id = newer; } let result = api.cover_art(&id); if results.send((id, result)).is_err() { break; } } }); Self { enabled: true, font_size, background: [16, 20, 28, 255], tx: Some(tx), rx: Some(rx), ..Self::default() } } /// Cache decoded images and discard stale results when the playing track changes. pub fn update(&mut self, cover: Option<(String, String)>) { if !self.enabled { return; } let (id, title) = cover.map_or((None, String::new()), |(id, title)| (Some(id), title)); self.title = title; if id != self.target { self.target = id.clone(); self.protocol = None; self.image_size = None; self.message = if id.is_some() { "Loading cover…" } else { "No cover available" } .into(); if let Some(id) = id { if let Some(index) = self.cache.iter().position(|(key, _)| key == &id) { let entry = self.cache.remove(index).unwrap(); self.show(entry.1.clone()); self.cache.push_back(entry); } else if let Some(tx) = &self.tx { let _ = tx.send(id); } } } let replies: Vec<_> = self .rx .as_ref() .map(|rx| rx.try_iter().collect()) .unwrap_or_default(); for (id, result) in replies { match result { Ok(image) => { if self.target.as_ref() == Some(&id) { self.show(image.clone()); } self.cache.retain(|(key, _)| key != &id); self.cache.push_back((id, image)); while self.cache.len() > 8 { self.cache.pop_front(); } } Err(e) if self.target.as_ref() == Some(&id) => self.message = e.to_string(), _ => {} } } } /// Rebuild the cached protocol when a theme changes the image's letterbox color. pub fn set_background(&mut self, color: ratatui::style::Color) { if let ratatui::style::Color::Rgb(r, g, b) = color { let background = [r, g, b, 255]; if self.background != background { self.background = background; let image = self .cache .iter() .find(|(id, _)| self.target.as_ref() == Some(id)) .map(|(_, image)| image.clone()); if let Some(image) = image { self.show(image); } } } } /// Fit the cover to its column without reserving unused rows below the image. pub fn height_for_width(&self, width: u16, max_height: u16) -> u16 { let (image_width, image_height) = self.image_size.unwrap_or((1, 1)); let (cell_width, cell_height) = if self.font_size.0 > 0 && self.font_size.1 > 0 { self.font_size } else { (8, 16) }; let pixels = u64::from(width) * u64::from(cell_width) * u64::from(image_height); let rows = pixels.div_ceil(u64::from(image_width.max(1)) * u64::from(cell_height)); rows.min(u64::from(max_height)) as u16 } fn show(&mut self, image: DynamicImage) { self.image_size = Some((image.width(), image.height())); let source = ImageSource::new(image, self.font_size, Rgba(self.background)); self.protocol = Some(StatefulProtocol::Sixel(StatefulSixel::new( source, self.font_size, std::env::var_os("TMUX").is_some(), ))); self.message.clear(); } } /// Bound decoded allocations as well as compressed downloads. pub fn decode(bytes: &[u8]) -> Result { let mut reader = ImageReader::new(Cursor::new(bytes)) .with_guessed_format() .context("Unknown cover format")?; let mut limits = image::Limits::default(); limits.max_image_width = Some(4096); limits.max_image_height = Some(4096); limits.max_alloc = Some(64 * 1024 * 1024); reader.limits(limits); let image = reader.decode().context("Cannot decode cover")?; if image.width() == 0 || image.height() == 0 { bail!("Empty cover"); } Ok(image.thumbnail(image.width().min(320), image.height().min(320))) } /// Query SIXEL support with a bounded poll; never leave a background stdin reader behind. pub fn terminal_font_size() -> Option<(u16, u16)> { let fallback = crossterm::terminal::window_size() .ok() .filter(|s| s.columns > 0 && s.rows > 0 && s.width >= s.columns && s.height >= s.rows) .map(|s| (s.width / s.columns, s.height / s.rows)) .unwrap_or((8, 16)); let mut stdout = std::io::stdout(); if stdout .write_all(b"\x1b[c\x1b[16t") .and_then(|_| stdout.flush()) .is_err() { return None; } let mut stdin = std::io::stdin(); let deadline = Instant::now() + Duration::from_millis(250); let mut response = Vec::new(); while Instant::now() < deadline && response.len() < 1024 { let mut fds = [rustix::event::PollFd::new( &stdin, rustix::event::PollFlags::IN, )]; let timeout = deadline .saturating_duration_since(Instant::now()) .as_millis() as i32; if rustix::event::poll(&mut fds, timeout).ok()? == 0 { break; } let mut bytes = [0; 128]; let n = stdin.read(&mut bytes).ok()?; if n == 0 { break; } response.extend_from_slice(&bytes[..n]); } let response = String::from_utf8_lossy(&response); query_response(&response, fallback) } fn query_response(response: &str, fallback: (u16, u16)) -> Option<(u16, u16)> { let supported = response.split("\x1b[?").skip(1).any(|s| { s.split_once('c') .is_some_and(|(params, _)| params.split(';').any(|p| p == "4")) }); if !supported { return None; } let font = response.split("\x1b[6;").skip(1).find_map(|s| { let (params, _) = s.split_once('t')?; let (height, width) = params.split_once(';')?; let (w, h) = (width.parse::().ok()?, height.parse::().ok()?); (w > 0 && h > 0 && w <= 256 && h <= 256).then_some((w, h)) }); Some(font.unwrap_or(fallback)) } #[cfg(test)] mod tests { use super::*; #[test] fn capabilities_require_sixel_and_nonzero_cells() { assert_eq!( query_response("\x1b[?62;4;22c\x1b[6;20;10t", (8, 16)), Some((10, 20)) ); assert_eq!( query_response("\x1b[?62;4c\x1b[6;0;0t", (8, 16)), Some((8, 16)) ); assert_eq!(query_response("\x1b[?62;24c", (8, 16)), None); assert_eq!(query_response("", (8, 16)), None); } #[test] fn old_cover_does_not_replace_current_track() { let (tx, rx) = mpsc::channel(); let mut art = Artwork { enabled: true, font_size: (8, 16), rx: Some(rx), ..Default::default() }; art.update(Some(("new".into(), "New".into()))); tx.send(("old".into(), Ok(DynamicImage::new_rgb8(96, 96)))) .unwrap(); art.update(Some(("new".into(), "New".into()))); assert!(art.protocol.is_none()); tx.send(("new".into(), Ok(DynamicImage::new_rgb8(96, 96)))) .unwrap(); art.update(Some(("new".into(), "New".into()))); assert!(art.protocol.is_some()); art.update(Some(("old".into(), "Old".into()))); assert!(art.protocol.is_some()); art.update(None); assert!(art.protocol.is_none()); } #[test] fn cover_height_tracks_aspect_ratio_cell_size_and_available_space() { let mut art = Artwork { font_size: (8, 16), ..Default::default() }; art.show(DynamicImage::new_rgb8(200, 200)); assert_eq!(art.height_for_width(26, 100), 13); assert_eq!(art.height_for_width(26, 6), 6); art.show(DynamicImage::new_rgb8(400, 200)); assert_eq!(art.height_for_width(26, 100), 7); art.show(DynamicImage::new_rgb8(200, 400)); assert_eq!(art.height_for_width(26, 100), 26); assert_eq!(art.height_for_width(26, 0), 0); assert_eq!(art.height_for_width(0, 100), 0); } #[test] fn rendering_emits_sixel_and_resizes_after_theme_change() { use ratatui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget}; let mut art = Artwork { enabled: true, font_size: (8, 16), ..Default::default() }; art.show(DynamicImage::new_rgb8(96, 96)); for (width, height) in [(24, 12), (12, 6)] { let area = Rect::new(0, 0, width, height); let mut buffer = Buffer::empty(area); ratatui_image::StatefulImage::default().render( area, &mut buffer, art.protocol.as_mut().unwrap(), ); assert!( buffer .content .iter() .any(|c| c.symbol().starts_with("\x1bP")) ); } art.set_background(crate::theme::Theme::Monokai.palette().bg); assert_eq!(art.background, [39, 40, 34, 255]); } #[test] fn decoding_rejects_non_images_and_excessive_dimensions() { assert!(decode(b"not an image").is_err()); let mut png = Cursor::new(Vec::new()); DynamicImage::new_rgb8(4097, 1) .write_to(&mut png, image::ImageFormat::Png) .unwrap(); assert!(decode(png.get_ref()).is_err()); let mut png = Cursor::new(Vec::new()); DynamicImage::new_rgb8(96, 96) .write_to(&mut png, image::ImageFormat::Png) .unwrap(); assert_eq!(decode(png.get_ref()).unwrap().width(), 96); } }