img.rs

  1use std::path::PathBuf;
  2use std::sync::Arc;
  3
  4use crate::{
  5    point, size, Bounds, DevicePixels, Element, ElementContext, ImageData, InteractiveElement,
  6    InteractiveElementState, Interactivity, IntoElement, LayoutId, Pixels, SharedUri, Size,
  7    StyleRefinement, Styled, UriOrPath,
  8};
  9use futures::FutureExt;
 10use media::core_video::CVImageBuffer;
 11use util::ResultExt;
 12
 13/// A source of image content.
 14#[derive(Clone, Debug)]
 15pub enum ImageSource {
 16    /// Image content will be loaded from provided URI at render time.
 17    Uri(SharedUri),
 18    /// Image content will be loaded from the provided file at render time.
 19    File(Arc<PathBuf>),
 20    /// Cached image data
 21    Data(Arc<ImageData>),
 22    // TODO: move surface definitions into mac platform module
 23    /// A CoreVideo image buffer
 24    Surface(CVImageBuffer),
 25}
 26
 27impl From<SharedUri> for ImageSource {
 28    fn from(value: SharedUri) -> Self {
 29        Self::Uri(value)
 30    }
 31}
 32
 33impl From<&'static str> for ImageSource {
 34    fn from(uri: &'static str) -> Self {
 35        Self::Uri(uri.into())
 36    }
 37}
 38
 39impl From<String> for ImageSource {
 40    fn from(uri: String) -> Self {
 41        Self::Uri(uri.into())
 42    }
 43}
 44
 45impl From<Arc<PathBuf>> for ImageSource {
 46    fn from(value: Arc<PathBuf>) -> Self {
 47        Self::File(value)
 48    }
 49}
 50
 51impl From<Arc<ImageData>> for ImageSource {
 52    fn from(value: Arc<ImageData>) -> Self {
 53        Self::Data(value)
 54    }
 55}
 56
 57impl From<CVImageBuffer> for ImageSource {
 58    fn from(value: CVImageBuffer) -> Self {
 59        Self::Surface(value)
 60    }
 61}
 62
 63/// An image element.
 64pub struct Img {
 65    interactivity: Interactivity,
 66    source: ImageSource,
 67    grayscale: bool,
 68}
 69
 70/// Create a new image element.
 71pub fn img(source: impl Into<ImageSource>) -> Img {
 72    Img {
 73        interactivity: Interactivity::default(),
 74        source: source.into(),
 75        grayscale: false,
 76    }
 77}
 78
 79impl Img {
 80    /// Set the image to be displayed in grayscale.
 81    pub fn grayscale(mut self, grayscale: bool) -> Self {
 82        self.grayscale = grayscale;
 83        self
 84    }
 85}
 86
 87impl Element for Img {
 88    type State = InteractiveElementState;
 89
 90    fn request_layout(
 91        &mut self,
 92        element_state: Option<Self::State>,
 93        cx: &mut ElementContext,
 94    ) -> (LayoutId, Self::State) {
 95        self.interactivity
 96            .layout(element_state, cx, |style, cx| cx.request_layout(&style, []))
 97    }
 98
 99    fn paint(
100        &mut self,
101        bounds: Bounds<Pixels>,
102        element_state: &mut Self::State,
103        cx: &mut ElementContext,
104    ) {
105        let source = self.source.clone();
106        self.interactivity.paint(
107            bounds,
108            bounds.size,
109            element_state,
110            cx,
111            |style, _scroll_offset, cx| {
112                let corner_radii = style.corner_radii.to_pixels(bounds.size, cx.rem_size());
113                cx.with_z_index(1, |cx| {
114                    match source {
115                        ImageSource::Uri(_) | ImageSource::File(_) => {
116                            let uri_or_path: UriOrPath = match source {
117                                ImageSource::Uri(uri) => uri.into(),
118                                ImageSource::File(path) => path.into(),
119                                _ => unreachable!(),
120                            };
121
122                            let image_future = cx.image_cache.get(uri_or_path.clone(), cx);
123                            if let Some(data) = image_future
124                                .clone()
125                                .now_or_never()
126                                .and_then(|result| result.ok())
127                            {
128                                let new_bounds = preserve_aspect_ratio(bounds, data.size());
129                                cx.paint_image(new_bounds, corner_radii, data, self.grayscale)
130                                    .log_err();
131                            } else {
132                                cx.spawn(|mut cx| async move {
133                                    if image_future.await.ok().is_some() {
134                                        cx.on_next_frame(|cx| cx.refresh());
135                                    }
136                                })
137                                .detach();
138                            }
139                        }
140
141                        ImageSource::Data(data) => {
142                            let new_bounds = preserve_aspect_ratio(bounds, data.size());
143                            cx.paint_image(new_bounds, corner_radii, data, self.grayscale)
144                                .log_err();
145                        }
146
147                        ImageSource::Surface(surface) => {
148                            let size = size(surface.width().into(), surface.height().into());
149                            let new_bounds = preserve_aspect_ratio(bounds, size);
150                            // TODO: Add support for corner_radii and grayscale.
151                            cx.paint_surface(new_bounds, surface);
152                        }
153                    };
154                });
155            },
156        )
157    }
158}
159
160impl IntoElement for Img {
161    type Element = Self;
162
163    fn element_id(&self) -> Option<crate::ElementId> {
164        self.interactivity.element_id.clone()
165    }
166
167    fn into_element(self) -> Self::Element {
168        self
169    }
170}
171
172impl Styled for Img {
173    fn style(&mut self) -> &mut StyleRefinement {
174        &mut self.interactivity.base_style
175    }
176}
177
178impl InteractiveElement for Img {
179    fn interactivity(&mut self) -> &mut Interactivity {
180        &mut self.interactivity
181    }
182}
183
184fn preserve_aspect_ratio(bounds: Bounds<Pixels>, image_size: Size<DevicePixels>) -> Bounds<Pixels> {
185    let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
186    let image_ratio = image_size.width / image_size.height;
187    let bounds_ratio = bounds.size.width / bounds.size.height;
188
189    let new_size = if bounds_ratio > image_ratio {
190        size(
191            image_size.width * (bounds.size.height / image_size.height),
192            bounds.size.height,
193        )
194    } else {
195        size(
196            bounds.size.width,
197            image_size.height * (bounds.size.width / image_size.width),
198        )
199    };
200
201    Bounds {
202        origin: point(
203            bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
204            bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
205        ),
206        size: new_size,
207    }
208}