image.rs

 1use anyhow::Result;
 2use base64::{
 3    Engine as _, alphabet,
 4    engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},
 5};
 6use gpui::{App, ClipboardItem, Image, ImageFormat, RenderImage, Window, img};
 7use std::sync::Arc;
 8use ui::{IntoElement, Styled, div, prelude::*};
 9
10use crate::outputs::OutputContent;
11
12/// ImageView renders an image inline in an editor, adapting to the line height to fit the image.
13pub struct ImageView {
14    clipboard_image: Arc<Image>,
15    height: u32,
16    width: u32,
17    image: Arc<RenderImage>,
18}
19
20pub const STANDARD_INDIFFERENT: GeneralPurpose = GeneralPurpose::new(
21    &alphabet::STANDARD,
22    GeneralPurposeConfig::new()
23        .with_encode_padding(false)
24        .with_decode_padding_mode(DecodePaddingMode::Indifferent),
25);
26
27impl ImageView {
28    pub fn from(base64_encoded_data: &str) -> Result<Self> {
29        let filtered =
30            base64_encoded_data.replace(&[' ', '\n', '\t', '\r', '\x0b', '\x0c'][..], "");
31        let bytes = STANDARD_INDIFFERENT.decode(filtered)?;
32
33        let format = image::guess_format(&bytes)?;
34
35        let mut data = image::load_from_memory_with_format(&bytes, format)?.into_rgba8();
36
37        // Convert from RGBA to BGRA.
38        for pixel in data.chunks_exact_mut(4) {
39            pixel.swap(0, 2);
40        }
41
42        let height = data.height();
43        let width = data.width();
44
45        let gpui_image_data = RenderImage::new(vec![image::Frame::new(data)]);
46
47        let format = match format {
48            image::ImageFormat::Png => ImageFormat::Png,
49            image::ImageFormat::Jpeg => ImageFormat::Jpeg,
50            image::ImageFormat::Gif => ImageFormat::Gif,
51            image::ImageFormat::WebP => ImageFormat::Webp,
52            image::ImageFormat::Tiff => ImageFormat::Tiff,
53            image::ImageFormat::Bmp => ImageFormat::Bmp,
54            image::ImageFormat::Ico => ImageFormat::Ico,
55            format => {
56                anyhow::bail!("unsupported image format {format:?}");
57            }
58        };
59
60        // Convert back to a GPUI image for use with the clipboard
61        let clipboard_image = Arc::new(Image::from_bytes(format, bytes));
62
63        Ok(ImageView {
64            clipboard_image,
65            height,
66            width,
67            image: Arc::new(gpui_image_data),
68        })
69    }
70}
71
72impl Render for ImageView {
73    fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
74        let line_height = window.line_height();
75
76        let (height, width) = if self.height as f32 / f32::from(line_height) == u8::MAX as f32 {
77            let height = u8::MAX as f32 * line_height;
78            let width = self.width as f32 * height / self.height as f32;
79            (height, width)
80        } else {
81            (self.height.into(), self.width.into())
82        };
83
84        let image = self.image.clone();
85
86        div().h(height).w(width).child(img(image))
87    }
88}
89
90impl OutputContent for ImageView {
91    fn clipboard_content(&self, _window: &Window, _cx: &App) -> Option<ClipboardItem> {
92        Some(ClipboardItem::new_image(self.clipboard_image.as_ref()))
93    }
94
95    fn has_clipboard_content(&self, _window: &Window, _cx: &App) -> bool {
96        true
97    }
98}