返回 CodeWhale
image_preview.rs
根目录 / crates / tui / src / tui / image_preview.rs
1 //! Terminal-cell thumbnails for attached images.
2 //!
3 //! The composer preview is drawn with ordinary cells, not a graphics
4 //! protocol: one cell holds two vertical pixels: the upper-half block
5 //! foreground and the lower as background. Every truecolor terminal can do
6 //! that - Windows Terminal, iTerm2, Terminal.app, GNOME Terminal, Konsole,
7 //! WezTerm - while kitty graphics and sixel cannot be assumed (and are not
8 //! available at all in Windows Terminal).
9 //!
10 //! Decoding is off-thread. A screenshot is megabytes of compressed data and
11 //! tens of milliseconds of CPU; doing that inline would stall the frame that
12 //! just received the paste. [`ThumbnailCache::request`] starts the decode and
13 //! [`ThumbnailCache::poll`] collects it on a later frame, so the composer
14 //! paints immediately and the picture appears when it is ready.
15 //!
16 //! Known limitation: only the first frame of an animated GIF is shown, and a
17 //! picture whose bytes are not valid PNG/JPEG/GIF/WebP simply has no preview
18 //! (the attachment itself still fails loudly at send time, where
19 //! `image_attach` validates it).
20
21 use std::collections::HashMap;
22 use std::path::{Path, PathBuf};
23 use std::sync::mpsc::{Receiver, Sender, channel};
24 use std::time::SystemTime;
25
26 use image::imageops::FilterType;
27 use image::{DynamicImage, GenericImageView, ImageReader};
28
29 /// Longest edge of the preview, in columns. Chosen so a landscape screenshot
30 /// stays a recognisable thumbnail without pushing the transcript away.
31 pub const PREVIEW_MAX_COLS: u16 = 40;
32
33 /// Longest edge of the preview, in rows. Eight rows is 16 pixel rows: enough
34 /// to tell a screenshot from a photo, small enough to leave the composer and
35 /// transcript room on an 24-row terminal.
36 pub const PREVIEW_MAX_ROWS: u16 = 8;
37
38 /// Decode budget for the background worker. A pasted screenshot is normally
39 /// well under this; anything larger is refused rather than decoded into
40 /// memory that the preview does not need anyway.
41 const PREVIEW_SOURCE_LIMIT: u64 = 32 * 1024 * 1024;
42
43 /// One cell of the preview: its upper and lower pixel, each absent when that
44 /// half is fully transparent. Absence is what lets the renderer keep the
45 /// theme's own background behind a transparent logo instead of painting it
46 /// black.
47 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
48 pub struct ThumbnailCell {
49 pub upper: Option<[u8; 3]>,
50 pub lower: Option<[u8; 3]>,
51 }
52
53 /// A decoded, cell-sized preview ready to paint.
54 #[derive(Debug, Clone, PartialEq, Eq)]
55 pub struct Thumbnail {
56 pub cols: u16,
57 pub rows: u16,
58 /// Row-major, `cols * rows` cells.
59 pub cells: Vec<ThumbnailCell>,
60 }
61
62 impl Thumbnail {
63 #[must_use]
64 pub fn cell(&self, col: u16, row: u16) -> Option<&ThumbnailCell> {
65 if col >= self.cols || row >= self.rows {
66 return None;
67 }
68 self.cells
69 .get(usize::from(row) * usize::from(self.cols) + usize::from(col))
70 }
71 }
72
73 /// The `(cols, rows)` box an image of `width x height` fills.
74 ///
75 /// A cell is half as wide as it is tall, so `cols` columns and `rows` rows
76 /// cover a `cols x 2*rows` pixel grid, and `cols / (2*rows)` must equal the
77 /// image's own aspect ratio. Reducing one axis and growing the other keeps
78 /// that ratio without letterboxing.
79 #[must_use]
80 pub fn thumbnail_size(width: u32, height: u32, max_cols: u16, max_rows: u16) -> (u16, u16) {
81 if width == 0 || height == 0 || max_cols == 0 || max_rows == 0 {
82 return (0, 0);
83 }
84 let aspect = f64::from(width) / f64::from(height);
85 let rows_at_max = f64::from(max_cols) / (2.0 * aspect);
86 let (cols, rows) = if rows_at_max >= f64::from(max_rows) {
87 // Max rows binds: use every row and widen to keep the ratio.
88 let cols = (2.0 * aspect * f64::from(max_rows)).round().max(1.0);
89 (cols, f64::from(max_rows))
90 } else {
91 // Max columns binds: use every column and shorten the height.
92 (f64::from(max_cols), rows_at_max.round().max(1.0))
93 };
94 (
95 u16::try_from(cols as u32)
96 .unwrap_or(max_cols)
97 .min(max_cols)
98 .max(1),
99 u16::try_from(rows as u32)
100 .unwrap_or(max_rows)
101 .min(max_rows)
102 .max(1),
103 )
104 }
105
106 /// Fit `image` into `max_cols x max_rows` cells and read every pixel pair.
107 #[must_use]
108 pub fn thumbnail_from_image(image: &DynamicImage, max_cols: u16, max_rows: u16) -> Thumbnail {
109 let (width, height) = image.dimensions();
110 let (cols, rows) = thumbnail_size(width, height, max_cols, max_rows);
111 if cols == 0 || rows == 0 {
112 return Thumbnail {
113 cols: 0,
114 rows: 0,
115 cells: Vec::new(),
116 };
117 }
118 // The sampling grid: one column per cell, two pixel rows per cell row.
119 let grid = image
120 .resize_exact(u32::from(cols), u32::from(rows) * 2, FilterType::Triangle)
121 .to_rgba8();
122 let mut cells = Vec::with_capacity(usize::from(cols) * usize::from(rows));
123 for row in 0..rows {
124 for col in 0..cols {
125 let upper = grid.get_pixel(u32::from(col), u32::from(row) * 2);
126 let lower = grid.get_pixel(u32::from(col), u32::from(row) * 2 + 1);
127 cells.push(ThumbnailCell {
128 upper: opaque_rgb(upper.0),
129 lower: opaque_rgb(lower.0),
130 });
131 }
132 }
133 Thumbnail { cols, rows, cells }
134 }
135
136 /// Fully transparent pixels are absent; anything else is its own RGB. A
137 /// half-transparent pixel is composited over the terminal's background by
138 /// simply dropping its alpha - the preview is an identification aid, not a
139 /// colour-accurate rendition.
140 fn opaque_rgb(pixel: [u8; 4]) -> Option<[u8; 3]> {
141 (pixel[3] >= 8).then_some([pixel[0], pixel[1], pixel[2]])
142 }
143
144 /// One cached preview, keyed by the file it came from.
145 #[derive(Debug, Clone)]
146 struct Entry {
147 stamp: (SystemTime, u64),
148 thumbnail: Thumbnail,
149 }
150
151 /// Concurrent preview decodes. A draft rarely holds more than a few pictures;
152 /// the cap keeps a many-file paste from spawning a thread per file.
153 const MAX_CONCURRENT_DECODES: usize = 4;
154
155 /// Decoded previews plus the worker that produces them.
156 #[derive(Debug)]
157 pub struct ThumbnailCache {
158 entries: HashMap<PathBuf, Entry>,
159 pending: std::collections::HashSet<PathBuf>,
160 /// The attachment list the cache was last reconciled against, so the
161 /// per-frame `track` call compares vectors instead of stating files.
162 live: Vec<PathBuf>,
163 tx: Sender<(PathBuf, (SystemTime, u64), Option<Thumbnail>)>,
164 rx: Receiver<(PathBuf, (SystemTime, u64), Option<Thumbnail>)>,
165 }
166
167 impl Default for ThumbnailCache {
168 fn default() -> Self {
169 Self::new()
170 }
171 }
172
173 impl ThumbnailCache {
174 #[must_use]
175 pub fn new() -> Self {
176 let (tx, rx) = channel();
177 Self {
178 entries: HashMap::new(),
179 pending: std::collections::HashSet::new(),
180 live: Vec::new(),
181 tx,
182 rx,
183 }
184 }
185
186 /// The cached preview for `path`, if one is ready.
187 #[must_use]
188 pub fn get(&self, path: &Path) -> Option<&Thumbnail> {
189 self.entries.get(path).map(|entry| &entry.thumbnail)
190 }
191
192 /// Ask for `path` to be decoded, unless it is already in flight.
193 ///
194 /// No filesystem call happens here: the stat that proves the file exists,
195 /// fits the budget and has not changed runs on the decode thread. That is
196 /// what keeps this callable from the paint path (#6149).
197 pub fn request(&mut self, path: &Path) {
198 // Bound the decode pool: a draft can hold many attachments, and one
199 // OS thread per picture would spike both memory and CPU on a small
200 // host. Anything over the pool is retried when `track` next sees the
201 // list change.
202 if self.pending.len() >= MAX_CONCURRENT_DECODES {
203 return;
204 }
205 let path_key = path.to_path_buf();
206 if !self.pending.insert(path_key.clone()) {
207 return;
208 }
209 let path = path_key.clone();
210 let tx = self.tx.clone();
211 // A fresh thread per decode keeps the frame loop free and dies with
212 // the request; there is never more than one per attached image. The
213 // stat lives inside this closure on purpose: `request` is reached from
214 // the paint path, and the blocking-calls gate only exempts calls that
215 // sit inside the dedicated thread (#6149).
216 if let Err(error) = std::thread::Builder::new()
217 .name("image-preview-decode".to_string())
218 .spawn(move || {
219 let published = std::fs::metadata(&path).ok().and_then(|metadata| {
220 if !metadata.is_file() || metadata.len() > PREVIEW_SOURCE_LIMIT {
221 return None;
222 }
223 let stamp = (metadata.modified().ok()?, metadata.len());
224 let thumbnail = decode_thumbnail(&path)?;
225 Some((stamp, thumbnail))
226 });
227 match published {
228 Some((stamp, thumbnail)) => {
229 let _ = tx.send((path, stamp, Some(thumbnail)));
230 }
231 None => {
232 // A failed decode still answers, so the pending entry
233 // clears instead of blocking that path forever. A
234 // retry needs a new request: `track` only re-requests
235 // when the attachment list changes.
236 let _ = tx.send((path, (SystemTime::UNIX_EPOCH, 0), None));
237 }
238 }
239 })
240 {
241 self.pending.remove(&path_key);
242 tracing::debug!(
243 path = %path_key.display(),
244 %error,
245 "failed to spawn image preview decode thread"
246 );
247 }
248 }
249
250 /// Keep the cache in step with what the composer shows, without touching
251 /// the filesystem on an unchanged draft.
252 ///
253 /// The render loop calls this every frame. It only compares the attachment
254 /// list, so a fast typist pays one vector comparison instead of one stat
255 /// per frame (#6149: blocking work never runs inline on the paint path).
256 pub fn track(&mut self, live: &[PathBuf]) {
257 if self.live == live {
258 return;
259 }
260 self.retain_only(live);
261 for path in live {
262 self.request(path);
263 }
264 self.live = live.to_vec();
265 }
266
267 /// Collect finished decodes. Called once per frame before painting.
268 ///
269 /// Returns whether a preview became available, so the caller can request
270 /// the repaint that draws it: the frame that handled the paste was drawn
271 /// before the decode finished, and an idle session may otherwise not draw
272 /// again for a long time.
273 pub fn poll(&mut self) -> bool {
274 let mut published = false;
275 while let Ok((path, stamp, thumbnail)) = self.rx.try_recv() {
276 // A decode the draft has already dropped (the attachment
277 // was removed while it ran) must not reappear in the
278 // cache: `retain_only` cleared its pending entry.
279 if !self.pending.remove(&path) {
280 continue;
281 }
282 match thumbnail {
283 Some(thumbnail) => {
284 if self
285 .entries
286 .get(&path)
287 .is_none_or(|entry| entry.stamp != stamp)
288 {
289 self.entries.insert(path, Entry { stamp, thumbnail });
290 published = true;
291 }
292 }
293 None => {
294 self.entries.remove(&path);
295 }
296 }
297 }
298 published
299 }
300
301 /// Drop previews nothing refers to any more, so a long session does not
302 /// retain every image the user ever attached.
303 fn retain_only(&mut self, live: &[PathBuf]) {
304 self.entries.retain(|path, _| live.contains(path));
305 self.pending.retain(|path| live.contains(path));
306 }
307 }
308
309 /// Decode one file into a thumbnail.
310 ///
311 /// Filesystem access happens in the caller's worker closure; this only reads
312 /// the bytes the stamp already proved exist.
313 fn decode_thumbnail(path: &Path) -> Option<Thumbnail> {
314 let reader = ImageReader::open(path).ok()?;
315 let mut reader = reader.with_guessed_format().ok()?;
316 // The preview never needs the full-resolution decode; bounding it keeps a
317 // huge screenshot from allocating its full pixel buffer for a 40x16 box.
318 let mut limits = image::Limits::default();
319 limits.max_alloc = Some(64 * 1024 * 1024);
320 limits.max_image_width = Some(16_384);
321 limits.max_image_height = Some(16_384);
322 reader.limits(limits);
323 let image = reader.decode().ok()?;
324 Some(thumbnail_from_image(
325 &image,
326 PREVIEW_MAX_COLS,
327 PREVIEW_MAX_ROWS,
328 ))
329 }
330
331 #[cfg(test)]
332 mod tests {
333 use super::*;
334
335 fn image_of(width: u32, height: u32) -> DynamicImage {
336 DynamicImage::ImageRgba8(image::RgbaImage::from_fn(width, height, |x, y| {
337 image::Rgba([x as u8, y as u8, 128, 255])
338 }))
339 }
340
341 #[test]
342 fn wide_image_uses_full_height_and_keeps_its_ratio() {
343 // 1200x848 is the manga page the feature was requested with. The row
344 // cap binds first, so the width follows from the aspect ratio.
345 let (cols, rows) = thumbnail_size(1200, 848, 40, 8);
346 assert_eq!(rows, 8);
347 let ratio = f64::from(cols) / (2.0 * f64::from(rows));
348 assert!(
349 (ratio - 1200.0 / 848.0).abs() < 0.05,
350 "cols={cols} rows={rows} ratio={ratio}"
351 );
352 }
353
354 #[test]
355 fn tall_image_uses_full_height_and_narrows_width() {
356 let (cols, rows) = thumbnail_size(600, 1600, 40, 8);
357 assert_eq!(rows, 8);
358 assert!((5..=8).contains(&cols), "cols={cols}");
359 }
360
361 #[test]
362 fn square_image_keeps_its_ratio() {
363 let (cols, rows) = thumbnail_size(1024, 1024, 40, 8);
364 assert_eq!(rows, 8);
365 // cols / (2*rows) = 1 for a square.
366 assert_eq!(cols, 16);
367 }
368
369 #[test]
370 fn degenerate_sizes_are_zero_not_a_panic() {
371 assert_eq!(thumbnail_size(0, 100, 40, 8), (0, 0));
372 assert_eq!(thumbnail_size(100, 0, 40, 8), (0, 0));
373 assert_eq!(thumbnail_size(100, 100, 0, 8), (0, 0));
374 assert_eq!(thumbnail_size(100, 100, 40, 0), (0, 0));
375 }
376
377 #[test]
378 fn thumbnail_covers_the_box_and_reads_both_halves() {
379 let thumb = thumbnail_from_image(&image_of(80, 40), 40, 8);
380 assert_eq!(
381 usize::from(thumb.cols) * usize::from(thumb.rows),
382 thumb.cells.len()
383 );
384 assert!(thumb.cells.iter().any(|cell| cell.upper.is_some()));
385 assert!(thumb.cells.iter().any(|cell| cell.lower.is_some()));
386 assert!(thumb.cell(0, 0).is_some());
387 assert!(thumb.cell(thumb.cols, 0).is_none());
388 }
389
390 #[test]
391 fn transparent_pixels_stay_absent_so_the_theme_shows_through() {
392 let image = DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
393 8,
394 8,
395 image::Rgba([0, 0, 0, 0]),
396 ));
397 let thumb = thumbnail_from_image(&image, 8, 4);
398 assert!(
399 thumb
400 .cells
401 .iter()
402 .all(|cell| cell.upper.is_none() && cell.lower.is_none()),
403 "{:?}",
404 thumb.cells
405 );
406 }
407
408 #[test]
409 fn cache_returns_nothing_until_the_decode_finishes_then_reuses_it() {
410 let dir = tempfile::tempdir().unwrap();
411 let path = dir.path().join("shot.png");
412 image_of(64, 32)
413 .save_with_format(&path, image::ImageFormat::Png)
414 .unwrap();
415 let mut cache = ThumbnailCache::new();
416 // Not requested yet.
417 assert!(cache.get(&path).is_none());
418 cache.request(&path);
419 // Poll until the worker publishes, bounded so a hang fails the test.
420 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
421 loop {
422 cache.poll();
423 if cache.get(&path).is_some() {
424 break;
425 }
426 assert!(
427 std::time::Instant::now() < deadline,
428 "decode did not finish"
429 );
430 std::thread::sleep(std::time::Duration::from_millis(10));
431 }
432 let first = cache.get(&path).unwrap().clone();
433 cache.request(&path);
434 // The re-decode is skipped by stamp comparison once it lands, but the
435 // worker still has to finish before the cache can say so.
436 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
437 loop {
438 cache.poll();
439 if cache.pending.is_empty() {
440 break;
441 }
442 assert!(
443 std::time::Instant::now() < deadline,
444 "re-decode did not settle"
445 );
446 std::thread::sleep(std::time::Duration::from_millis(10));
447 }
448 assert_eq!(cache.get(&path).unwrap(), &first);
449 }
450
451 #[test]
452 fn poll_reports_a_newly_published_preview_once() {
453 let dir = tempfile::tempdir().unwrap();
454 let path = dir.path().join("shot.png");
455 image_of(32, 16)
456 .save_with_format(&path, image::ImageFormat::Png)
457 .unwrap();
458 let mut cache = ThumbnailCache::new();
459 cache.request(&path);
460 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
461 let mut published = false;
462 while !published {
463 published = cache.poll();
464 assert!(
465 std::time::Instant::now() < deadline,
466 "decode did not finish"
467 );
468 std::thread::sleep(std::time::Duration::from_millis(10));
469 }
470 // The second poll has nothing new, so the caller asks for no extra
471 // frame: a permanent `true` would repaint forever.
472 assert!(!cache.poll());
473 }
474
475 #[test]
476 fn track_drops_previews_the_composer_no_longer_shows() {
477 let dir = tempfile::tempdir().unwrap();
478 let kept = dir.path().join("kept.png");
479 let dropped = dir.path().join("dropped.png");
480 image_of(16, 16)
481 .save_with_format(&kept, image::ImageFormat::Png)
482 .unwrap();
483 image_of(16, 16)
484 .save_with_format(&dropped, image::ImageFormat::Png)
485 .unwrap();
486 let mut cache = ThumbnailCache::new();
487 cache.request(&kept);
488 cache.request(&dropped);
489 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
490 while cache.entries.len() < 2 {
491 cache.poll();
492 assert!(
493 std::time::Instant::now() < deadline,
494 "decodes did not finish"
495 );
496 std::thread::sleep(std::time::Duration::from_millis(10));
497 }
498 cache.track(std::slice::from_ref(&kept));
499 assert!(cache.get(&kept).is_some());
500 assert!(cache.get(&dropped).is_none());
501 }
502
503 #[test]
504 fn missing_and_non_image_files_never_produce_a_preview() {
505 let dir = tempfile::tempdir().unwrap();
506 let text = dir.path().join("notes.txt");
507 std::fs::write(&text, b"not an image").unwrap();
508 let mut cache = ThumbnailCache::new();
509 cache.request(&dir.path().join("absent.png"));
510 cache.request(&text);
511 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
512 loop {
513 cache.poll();
514 if cache.pending.is_empty() {
515 break;
516 }
517 assert!(
518 std::time::Instant::now() < deadline,
519 "decode did not settle"
520 );
521 std::thread::sleep(std::time::Duration::from_millis(10));
522 }
523 assert!(cache.get(&text).is_none());
524 }
525 }
526
526 lines RUST