iterm2 image protocol: make image fit to terminal dimensions

when the size is set to auto, we'd essentially take the image as-is
and overflow the terminal.

This commit makes auto scale down the image to fit the terminal dimensions
if it is too big.
This commit is contained in:
Wez Furlong committed 2021-03-13 13:14:46 -08:00
1 parent 333f5f9750
commit e5974ad86f
1 file changed
+26 -4
+26 -4
View File
@@ -1599,10 +1599,32 @@ impl TerminalState {
let aspect = decoded_image.width() as f32 / decoded_image.height() as f32;
let (width, height) = match (width, height) {
(None, None) => (
decoded_image.width() as usize,
decoded_image.height() as usize,
),
(None, None) => {
// Take the image's native size
let width = decoded_image.width() as usize;
let height = decoded_image.height() as usize;
// but ensure that it fits
if width as usize > self.pixel_width || height as usize > self.pixel_height {
let width = width as f32;
let height = height as f32;
let mut candidates = vec![];
let x_scale = self.pixel_width as f32 / width;
if height * x_scale <= self.pixel_height as f32 {
candidates.push((self.pixel_width, (height * x_scale) as usize));
}
let y_scale = self.pixel_height as f32 / height;
if width * y_scale <= self.pixel_width as f32 {
candidates.push(((width * y_scale) as usize, self.pixel_height));
}
candidates.sort_by(|a, b| (a.0 * a.1).cmp(&(b.0 * b.1)));
candidates.pop().unwrap()
} else {
(width, height)
}
}
(Some(w), None) => {
let h = w as f32 / aspect;
(w, h as usize)