返回 CodeWhale
attachment_preview.rs
根目录 / crates / tui / src / tui / widgets / attachment_preview.rs
1 //! The composer's image thumbnails.
2 //!
3 //! Placed between the pending-input preview and the composer, so pasted
4 //! screenshots are visible before they are sent. The pictures are drawn by
5 //! [`crate::tui::image_preview`] as cell-sized half blocks, which every
6 //! truecolor terminal can render - no kitty graphics or sixel required.
7 //!
8 //! Attachments are laid out left to right and share the available width, so a
9 //! draft holding several screenshots previews all of them instead of only the
10 //! first. Zero rows while nothing is attached, while the decode is still
11 //! running, or when the terminal is in ASCII-safe mode, so the transcript
12 //! never loses rows to a preview that cannot be drawn.
13
14 use std::path::PathBuf;
15
16 use ratatui::buffer::Buffer;
17 use ratatui::layout::Rect;
18 use ratatui::style::{Color, Style};
19
20 use crate::tui::app::App;
21 use crate::tui::widgets::Renderable;
22 use codewhale_palette as palette;
23
24 /// Upper half block: foreground paints the top pixel, background the bottom.
25 const UPPER_HALF: &str = "\u{2580}";
26 /// Lower half block, for a cell whose top pixel is transparent.
27 const LOWER_HALF: &str = "\u{2584}";
28
29 /// Narrowest a single thumbnail may get before it stops reading as a picture.
30 const MIN_SLOT_COLS: u16 = 6;
31
32 /// The image files the draft currently attaches, in attachment order.
33 #[must_use]
34 pub fn attached_image_paths(app: &App) -> Vec<PathBuf> {
35 codewhale_core::media_attachment_references(&app.input)
36 .into_iter()
37 .filter(|reference| reference.kind == "image")
38 .map(|reference| PathBuf::from(reference.path))
39 .collect()
40 }
41
42 /// Widget drawing every attached image as a row of cell thumbnails.
43 pub struct AttachmentPreviewWidget<'a> {
44 app: &'a App,
45 paths: Vec<PathBuf>,
46 }
47
48 impl<'a> AttachmentPreviewWidget<'a> {
49 /// `None` when the draft has no image to preview.
50 #[must_use]
51 pub fn for_app(app: &'a App) -> Option<Self> {
52 let paths = attached_image_paths(app);
53 (!paths.is_empty()).then_some(Self { app, paths })
54 }
55
56 /// Width one thumbnail gets when `count` pictures share `width`.
57 fn slot_width(width: u16, count: usize) -> u16 {
58 let count = u16::try_from(count.max(1)).unwrap_or(u16::MAX);
59 (width / count).max(MIN_SLOT_COLS)
60 }
61 }
62
63 impl Renderable for AttachmentPreviewWidget<'_> {
64 fn render(&self, area: Rect, buf: &mut Buffer) {
65 if area.width == 0 || area.height == 0 {
66 return;
67 }
68 let slot = Self::slot_width(area.width, self.paths.len());
69 let right = area.x.saturating_add(area.width);
70 let mut max_rows = 0u16;
71 let mut drawn = 0usize;
72
73 for (index, path) in self.paths.iter().enumerate() {
74 let Some(thumbnail) = self.app.attachment_preview.get(path) else {
75 continue;
76 };
77 let x = area.x.saturating_add(
78 u16::try_from(index)
79 .unwrap_or(u16::MAX)
80 .saturating_mul(slot),
81 );
82 if x >= right {
83 break;
84 }
85 let width = slot.min(right - x);
86 // A split pane can be narrower than a thumbnail's natural width.
87 // Decimate the sampled grid instead of dropping the picture: the
88 // larger of the two overflow factors keeps the aspect ratio, so a
89 // narrow slot shows a smaller thumbnail rather than nothing.
90 let step = thumbnail
91 .cols
92 .div_ceil(width.max(1))
93 .max(thumbnail.rows.div_ceil(area.height.max(1)))
94 .max(1);
95 let cols = thumbnail.cols / step;
96 let rows = thumbnail.rows / step;
97 if cols == 0 || rows == 0 {
98 continue;
99 }
100 drawn += 1;
101 max_rows = max_rows.max(rows);
102
103 for row in 0..rows {
104 for col in 0..cols {
105 let Some(cell) = thumbnail.cell(col * step, row * step) else {
106 continue;
107 };
108 let Some(buffer_cell) = buf.cell_mut((x + col, area.y + row)) else {
109 continue;
110 };
111 match (cell.upper, cell.lower) {
112 (Some(upper), Some(lower)) => {
113 buffer_cell.set_symbol(UPPER_HALF);
114 buffer_cell
115 .set_fg(Color::Rgb(upper[0], upper[1], upper[2]))
116 .set_bg(Color::Rgb(lower[0], lower[1], lower[2]));
117 }
118 (Some(upper), None) => {
119 buffer_cell.set_symbol(UPPER_HALF);
120 buffer_cell.set_fg(Color::Rgb(upper[0], upper[1], upper[2]));
121 }
122 (None, Some(lower)) => {
123 buffer_cell.set_symbol(LOWER_HALF);
124 buffer_cell.set_fg(Color::Rgb(lower[0], lower[1], lower[2]));
125 }
126 (None, None) => {}
127 }
128 }
129 }
130 }
131
132 if drawn == 0 || area.height <= max_rows {
133 return;
134 }
135 let label = if self.paths.len() == 1 {
136 let name = self
137 .paths
138 .first()
139 .and_then(|path| path.file_name())
140 .and_then(|name| name.to_str())
141 .unwrap_or("image");
142 name.to_string()
143 } else {
144 format!("{} images", self.paths.len())
145 };
146 buf.set_stringn(
147 area.x,
148 area.y + max_rows,
149 label,
150 usize::from(area.width),
151 Style::default().fg(palette::TEXT_DIM),
152 );
153 }
154
155 fn desired_height(&self, width: u16) -> u16 {
156 if width == 0 || crate::tui::color_compat::ascii_safe_enabled() {
157 return 0;
158 }
159 let slot = Self::slot_width(width, self.paths.len());
160 let mut max_rows = 0u16;
161 for path in &self.paths {
162 let Some(thumbnail) = self.app.attachment_preview.get(path) else {
163 continue;
164 };
165 if thumbnail.cols == 0 || thumbnail.rows == 0 {
166 continue;
167 }
168 // Same decimation the render uses, so the reserved rows match what
169 // is actually painted.
170 let step = thumbnail.cols.div_ceil(slot).max(1);
171 max_rows = max_rows.max(thumbnail.rows / step);
172 }
173 if max_rows == 0 {
174 return 0;
175 }
176 // One caption row under the pictures.
177 max_rows.saturating_add(1)
178 }
179 }
180
181 #[cfg(test)]
182 mod tests {
183 use super::*;
184 use crate::tui::app::App;
185 use crate::tui::test_support::test_tui_options;
186
187 fn app_with_attachments(paths: &[&str]) -> App {
188 let mut app = App::new(
189 test_tui_options("."),
190 &codewhale_runtime::config::Config::default(),
191 );
192 app.input = paths
193 .iter()
194 .map(|path| format!("[Attached image: 8x4 PNG (2KB) at {path}]"))
195 .collect::<Vec<_>>()
196 .join("\n");
197 app
198 }
199
200 #[test]
201 fn every_attached_image_is_read_from_the_placeholder_lines() {
202 let app = app_with_attachments(&["/tmp/one.png", "/tmp/two.png"]);
203 assert_eq!(
204 attached_image_paths(&app),
205 vec![PathBuf::from("/tmp/one.png"), PathBuf::from("/tmp/two.png")]
206 );
207 }
208
209 #[test]
210 fn a_draft_without_an_attachment_has_no_widget() {
211 let app = App::new(
212 test_tui_options("."),
213 &codewhale_runtime::config::Config::default(),
214 );
215 assert!(AttachmentPreviewWidget::for_app(&app).is_none());
216 }
217
218 #[test]
219 fn an_undecoded_attachment_takes_no_rows() {
220 let app = app_with_attachments(&["/tmp/never-decoded.png"]);
221 let widget = AttachmentPreviewWidget::for_app(&app).expect("widget");
222 assert_eq!(widget.desired_height(80), 0);
223 }
224
225 #[test]
226 fn slots_share_the_width_and_never_fall_below_the_floor() {
227 assert_eq!(AttachmentPreviewWidget::slot_width(120, 3), 40);
228 assert_eq!(AttachmentPreviewWidget::slot_width(120, 1), 120);
229 assert_eq!(AttachmentPreviewWidget::slot_width(20, 8), MIN_SLOT_COLS);
230 }
231
232 #[test]
233 fn a_widget_keeps_every_attached_path() {
234 let app = app_with_attachments(&["/tmp/a.png", "/tmp/b.png", "/tmp/c.png"]);
235 let widget = AttachmentPreviewWidget::for_app(&app).expect("widget");
236 assert_eq!(widget.paths.len(), 3);
237 }
238 }
239
239 lines RUST