octo-tui/src/artwork.rs
src/artwork.rsRaw
1use crate::api::Api;
2use anyhow::{Context, Result, bail};
3use image::{DynamicImage, ImageReader, Rgba};
4use ratatui_image::protocol::{ImageSource, StatefulProtocol, sixel::StatefulSixel};
5use std::{
6 collections::VecDeque,
7 io::{Cursor, Read, Write},
8 sync::{
9 Arc,
10 mpsc::{self, Receiver, Sender},
11 },
12 time::{Duration, Instant},
13};
14
15#[derive(Default)]
16pub struct Artwork {
17 pub enabled: bool,
18 pub protocol: Option<StatefulProtocol>,
19 pub message: String,
20 pub title: String,
21 target: Option<String>,
22 image_size: Option<(u32, u32)>,
23 font_size: (u16, u16),
24 background: [u8; 4],
25 cache: VecDeque<(String, DynamicImage)>,
26 tx: Option<Sender<String>>,
27 rx: Option<Receiver<(String, Result<DynamicImage>)>>,
28}
29
30impl Artwork {
31 /// Coalesce playback changes on a dedicated worker so covers cannot block music requests.
32 pub fn new(api: Arc<Api>, font_size: (u16, u16)) -> Self {
33 let (tx, jobs) = mpsc::channel::<String>();
34 let (results, rx) = mpsc::channel();
35 std::thread::spawn(move || {
36 while let Ok(mut id) = jobs.recv() {
37 for newer in jobs.try_iter() {
38 id = newer;
39 }
40 let result = api.cover_art(&id);
41 if results.send((id, result)).is_err() {
42 break;
43 }
44 }
45 });
46 Self {
47 enabled: true,
48 font_size,
49 background: [16, 20, 28, 255],
50 tx: Some(tx),
51 rx: Some(rx),
52 ..Self::default()
53 }
54 }
55 /// Cache decoded images and discard stale results when the playing track changes.
56 pub fn update(&mut self, cover: Option<(String, String)>) {
57 if !self.enabled {
58 return;
59 }
60 let (id, title) = cover.map_or((None, String::new()), |(id, title)| (Some(id), title));
61 self.title = title;
62 if id != self.target {
63 self.target = id.clone();
64 self.protocol = None;
65 self.image_size = None;
66 self.message = if id.is_some() {
67 "Loading cover…"
68 } else {
69 "No cover available"
70 }
71 .into();
72 if let Some(id) = id {
73 if let Some(index) = self.cache.iter().position(|(key, _)| key == &id) {
74 let entry = self.cache.remove(index).unwrap();
75 self.show(entry.1.clone());
76 self.cache.push_back(entry);
77 } else if let Some(tx) = &self.tx {
78 let _ = tx.send(id);
79 }
80 }
81 }
82 let replies: Vec<_> = self
83 .rx
84 .as_ref()
85 .map(|rx| rx.try_iter().collect())
86 .unwrap_or_default();
87 for (id, result) in replies {
88 match result {
89 Ok(image) => {
90 if self.target.as_ref() == Some(&id) {
91 self.show(image.clone());
92 }
93 self.cache.retain(|(key, _)| key != &id);
94 self.cache.push_back((id, image));
95 while self.cache.len() > 8 {
96 self.cache.pop_front();
97 }
98 }
99 Err(e) if self.target.as_ref() == Some(&id) => self.message = e.to_string(),
100 _ => {}
101 }
102 }
103 }
104 /// Rebuild the cached protocol when a theme changes the image's letterbox color.
105 pub fn set_background(&mut self, color: ratatui::style::Color) {
106 if let ratatui::style::Color::Rgb(r, g, b) = color {
107 let background = [r, g, b, 255];
108 if self.background != background {
109 self.background = background;
110 let image = self
111 .cache
112 .iter()
113 .find(|(id, _)| self.target.as_ref() == Some(id))
114 .map(|(_, image)| image.clone());
115 if let Some(image) = image {
116 self.show(image);
117 }
118 }
119 }
120 }
121 /// Fit the cover to its column without reserving unused rows below the image.
122 pub fn height_for_width(&self, width: u16, max_height: u16) -> u16 {
123 let (image_width, image_height) = self.image_size.unwrap_or((1, 1));
124 let (cell_width, cell_height) = if self.font_size.0 > 0 && self.font_size.1 > 0 {
125 self.font_size
126 } else {
127 (8, 16)
128 };
129 let pixels = u64::from(width) * u64::from(cell_width) * u64::from(image_height);
130 let rows = pixels.div_ceil(u64::from(image_width.max(1)) * u64::from(cell_height));
131 rows.min(u64::from(max_height)) as u16
132 }
133 fn show(&mut self, image: DynamicImage) {
134 self.image_size = Some((image.width(), image.height()));
135 let source = ImageSource::new(image, self.font_size, Rgba(self.background));
136 self.protocol = Some(StatefulProtocol::Sixel(StatefulSixel::new(
137 source,
138 self.font_size,
139 std::env::var_os("TMUX").is_some(),
140 )));
141 self.message.clear();
142 }
143}
144
145/// Bound decoded allocations as well as compressed downloads.
146pub fn decode(bytes: &[u8]) -> Result<DynamicImage> {
147 let mut reader = ImageReader::new(Cursor::new(bytes))
148 .with_guessed_format()
149 .context("Unknown cover format")?;
150 let mut limits = image::Limits::default();
151 limits.max_image_width = Some(4096);
152 limits.max_image_height = Some(4096);
153 limits.max_alloc = Some(64 * 1024 * 1024);
154 reader.limits(limits);
155 let image = reader.decode().context("Cannot decode cover")?;
156 if image.width() == 0 || image.height() == 0 {
157 bail!("Empty cover");
158 }
159 Ok(image.thumbnail(image.width().min(320), image.height().min(320)))
160}
161
162/// Query SIXEL support with a bounded poll; never leave a background stdin reader behind.
163pub fn terminal_font_size() -> Option<(u16, u16)> {
164 let fallback = crossterm::terminal::window_size()
165 .ok()
166 .filter(|s| s.columns > 0 && s.rows > 0 && s.width >= s.columns && s.height >= s.rows)
167 .map(|s| (s.width / s.columns, s.height / s.rows))
168 .unwrap_or((8, 16));
169 let mut stdout = std::io::stdout();
170 if stdout
171 .write_all(b"\x1b[c\x1b[16t")
172 .and_then(|_| stdout.flush())
173 .is_err()
174 {
175 return None;
176 }
177 let mut stdin = std::io::stdin();
178 let deadline = Instant::now() + Duration::from_millis(250);
179 let mut response = Vec::new();
180 while Instant::now() < deadline && response.len() < 1024 {
181 let mut fds = [rustix::event::PollFd::new(
182 &stdin,
183 rustix::event::PollFlags::IN,
184 )];
185 let timeout = deadline
186 .saturating_duration_since(Instant::now())
187 .as_millis() as i32;
188 if rustix::event::poll(&mut fds, timeout).ok()? == 0 {
189 break;
190 }
191 let mut bytes = [0; 128];
192 let n = stdin.read(&mut bytes).ok()?;
193 if n == 0 {
194 break;
195 }
196 response.extend_from_slice(&bytes[..n]);
197 }
198 let response = String::from_utf8_lossy(&response);
199 query_response(&response, fallback)
200}
201
202fn query_response(response: &str, fallback: (u16, u16)) -> Option<(u16, u16)> {
203 let supported = response.split("\x1b[?").skip(1).any(|s| {
204 s.split_once('c')
205 .is_some_and(|(params, _)| params.split(';').any(|p| p == "4"))
206 });
207 if !supported {
208 return None;
209 }
210 let font = response.split("\x1b[6;").skip(1).find_map(|s| {
211 let (params, _) = s.split_once('t')?;
212 let (height, width) = params.split_once(';')?;
213 let (w, h) = (width.parse::<u16>().ok()?, height.parse::<u16>().ok()?);
214 (w > 0 && h > 0 && w <= 256 && h <= 256).then_some((w, h))
215 });
216 Some(font.unwrap_or(fallback))
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 #[test]
223 fn capabilities_require_sixel_and_nonzero_cells() {
224 assert_eq!(
225 query_response("\x1b[?62;4;22c\x1b[6;20;10t", (8, 16)),
226 Some((10, 20))
227 );
228 assert_eq!(
229 query_response("\x1b[?62;4c\x1b[6;0;0t", (8, 16)),
230 Some((8, 16))
231 );
232 assert_eq!(query_response("\x1b[?62;24c", (8, 16)), None);
233 assert_eq!(query_response("", (8, 16)), None);
234 }
235 #[test]
236 fn old_cover_does_not_replace_current_track() {
237 let (tx, rx) = mpsc::channel();
238 let mut art = Artwork {
239 enabled: true,
240 font_size: (8, 16),
241 rx: Some(rx),
242 ..Default::default()
243 };
244 art.update(Some(("new".into(), "New".into())));
245 tx.send(("old".into(), Ok(DynamicImage::new_rgb8(96, 96))))
246 .unwrap();
247 art.update(Some(("new".into(), "New".into())));
248 assert!(art.protocol.is_none());
249 tx.send(("new".into(), Ok(DynamicImage::new_rgb8(96, 96))))
250 .unwrap();
251 art.update(Some(("new".into(), "New".into())));
252 assert!(art.protocol.is_some());
253 art.update(Some(("old".into(), "Old".into())));
254 assert!(art.protocol.is_some());
255 art.update(None);
256 assert!(art.protocol.is_none());
257 }
258 #[test]
259 fn cover_height_tracks_aspect_ratio_cell_size_and_available_space() {
260 let mut art = Artwork {
261 font_size: (8, 16),
262 ..Default::default()
263 };
264 art.show(DynamicImage::new_rgb8(200, 200));
265 assert_eq!(art.height_for_width(26, 100), 13);
266 assert_eq!(art.height_for_width(26, 6), 6);
267 art.show(DynamicImage::new_rgb8(400, 200));
268 assert_eq!(art.height_for_width(26, 100), 7);
269 art.show(DynamicImage::new_rgb8(200, 400));
270 assert_eq!(art.height_for_width(26, 100), 26);
271 assert_eq!(art.height_for_width(26, 0), 0);
272 assert_eq!(art.height_for_width(0, 100), 0);
273 }
274
275 #[test]
276 fn rendering_emits_sixel_and_resizes_after_theme_change() {
277 use ratatui::{buffer::Buffer, layout::Rect, widgets::StatefulWidget};
278 let mut art = Artwork {
279 enabled: true,
280 font_size: (8, 16),
281 ..Default::default()
282 };
283 art.show(DynamicImage::new_rgb8(96, 96));
284 for (width, height) in [(24, 12), (12, 6)] {
285 let area = Rect::new(0, 0, width, height);
286 let mut buffer = Buffer::empty(area);
287 ratatui_image::StatefulImage::default().render(
288 area,
289 &mut buffer,
290 art.protocol.as_mut().unwrap(),
291 );
292 assert!(
293 buffer
294 .content
295 .iter()
296 .any(|c| c.symbol().starts_with("\x1bP"))
297 );
298 }
299 art.set_background(crate::theme::Theme::Monokai.palette().bg);
300 assert_eq!(art.background, [39, 40, 34, 255]);
301 }
302 #[test]
303 fn decoding_rejects_non_images_and_excessive_dimensions() {
304 assert!(decode(b"not an image").is_err());
305 let mut png = Cursor::new(Vec::new());
306 DynamicImage::new_rgb8(4097, 1)
307 .write_to(&mut png, image::ImageFormat::Png)
308 .unwrap();
309 assert!(decode(png.get_ref()).is_err());
310 let mut png = Cursor::new(Vec::new());
311 DynamicImage::new_rgb8(96, 96)
312 .write_to(&mut png, image::ImageFormat::Png)
313 .unwrap();
314 assert_eq!(decode(png.get_ref()).unwrap().width(), 96);
315 }
316}