1use crate::{
2 px, swap_rgba_pa_to_bgra, AbsoluteLength, AnyElement, App, Asset, AssetLogger, Bounds,
3 DefiniteLength, Element, ElementId, GlobalElementId, Hitbox, Image, InteractiveElement,
4 Interactivity, IntoElement, LayoutId, Length, ObjectFit, Pixels, RenderImage, Resource,
5 SharedString, SharedUri, StyleRefinement, Styled, SvgSize, Task, Window,
6};
7use anyhow::{anyhow, Result};
8
9use futures::{AsyncReadExt, Future};
10use image::{
11 codecs::{gif::GifDecoder, webp::WebPDecoder},
12 AnimationDecoder, DynamicImage, Frame, ImageBuffer, ImageError, ImageFormat, Rgba,
13};
14use smallvec::SmallVec;
15use std::{
16 fs,
17 io::{self, Cursor},
18 ops::{Deref, DerefMut},
19 path::{Path, PathBuf},
20 str::FromStr,
21 sync::Arc,
22 time::{Duration, Instant},
23};
24use thiserror::Error;
25use util::ResultExt;
26
27use super::{FocusableElement, Stateful, StatefulInteractiveElement};
28
29/// The delay before showing the loading state.
30pub const LOADING_DELAY: Duration = Duration::from_millis(200);
31
32/// A type alias to the resource loader that the `img()` element uses.
33///
34/// Note: that this is only for Resources, like URLs or file paths.
35/// Custom loaders, or external images will not use this asset loader
36pub type ImgResourceLoader = AssetLogger<ImageAssetLoader>;
37
38/// A source of image content.
39#[derive(Clone)]
40pub enum ImageSource {
41 /// The image content will be loaded from some resource location
42 Resource(Resource),
43 /// Cached image data
44 Render(Arc<RenderImage>),
45 /// Cached image data
46 Image(Arc<Image>),
47 /// A custom loading function to use
48 Custom(Arc<dyn Fn(&mut Window, &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>>>),
49}
50
51fn is_uri(uri: &str) -> bool {
52 http_client::Uri::from_str(uri).is_ok()
53}
54
55impl From<SharedUri> for ImageSource {
56 fn from(value: SharedUri) -> Self {
57 Self::Resource(Resource::Uri(value))
58 }
59}
60
61impl<'a> From<&'a str> for ImageSource {
62 fn from(s: &'a str) -> Self {
63 if is_uri(s) {
64 Self::Resource(Resource::Uri(s.to_string().into()))
65 } else {
66 Self::Resource(Resource::Embedded(s.to_string().into()))
67 }
68 }
69}
70
71impl From<String> for ImageSource {
72 fn from(s: String) -> Self {
73 if is_uri(&s) {
74 Self::Resource(Resource::Uri(s.into()))
75 } else {
76 Self::Resource(Resource::Embedded(s.into()))
77 }
78 }
79}
80
81impl From<SharedString> for ImageSource {
82 fn from(s: SharedString) -> Self {
83 s.as_ref().into()
84 }
85}
86
87impl From<&Path> for ImageSource {
88 fn from(value: &Path) -> Self {
89 Self::Resource(value.to_path_buf().into())
90 }
91}
92
93impl From<Arc<Path>> for ImageSource {
94 fn from(value: Arc<Path>) -> Self {
95 Self::Resource(value.into())
96 }
97}
98
99impl From<PathBuf> for ImageSource {
100 fn from(value: PathBuf) -> Self {
101 Self::Resource(value.into())
102 }
103}
104
105impl From<Arc<RenderImage>> for ImageSource {
106 fn from(value: Arc<RenderImage>) -> Self {
107 Self::Render(value)
108 }
109}
110
111impl From<Arc<Image>> for ImageSource {
112 fn from(value: Arc<Image>) -> Self {
113 Self::Image(value)
114 }
115}
116
117impl<
118 F: Fn(&mut Window, &mut App) -> Option<Result<Arc<RenderImage>, ImageCacheError>> + 'static,
119 > From<F> for ImageSource
120{
121 fn from(value: F) -> Self {
122 Self::Custom(Arc::new(value))
123 }
124}
125
126/// The style of an image element.
127pub struct ImageStyle {
128 grayscale: bool,
129 object_fit: ObjectFit,
130 loading: Option<Box<dyn Fn() -> AnyElement>>,
131 fallback: Option<Box<dyn Fn() -> AnyElement>>,
132}
133
134impl Default for ImageStyle {
135 fn default() -> Self {
136 Self {
137 grayscale: false,
138 object_fit: ObjectFit::Contain,
139 loading: None,
140 fallback: None,
141 }
142 }
143}
144
145/// Style an image element.
146pub trait StyledImage: Sized {
147 /// Get a mutable [ImageStyle] from the element.
148 fn image_style(&mut self) -> &mut ImageStyle;
149
150 /// Set the image to be displayed in grayscale.
151 fn grayscale(mut self, grayscale: bool) -> Self {
152 self.image_style().grayscale = grayscale;
153 self
154 }
155
156 /// Set the object fit for the image.
157 fn object_fit(mut self, object_fit: ObjectFit) -> Self {
158 self.image_style().object_fit = object_fit;
159 self
160 }
161
162 /// Set the object fit for the image.
163 fn with_fallback(mut self, fallback: impl Fn() -> AnyElement + 'static) -> Self {
164 self.image_style().fallback = Some(Box::new(fallback));
165 self
166 }
167
168 /// Set the object fit for the image.
169 fn with_loading(mut self, loading: impl Fn() -> AnyElement + 'static) -> Self {
170 self.image_style().loading = Some(Box::new(loading));
171 self
172 }
173}
174
175impl StyledImage for Img {
176 fn image_style(&mut self) -> &mut ImageStyle {
177 &mut self.style
178 }
179}
180
181impl StyledImage for Stateful<Img> {
182 fn image_style(&mut self) -> &mut ImageStyle {
183 &mut self.element.style
184 }
185}
186
187/// An image element.
188pub struct Img {
189 interactivity: Interactivity,
190 source: ImageSource,
191 style: ImageStyle,
192}
193
194/// Create a new image element.
195pub fn img(source: impl Into<ImageSource>) -> Img {
196 Img {
197 interactivity: Interactivity::default(),
198 source: source.into(),
199 style: ImageStyle::default(),
200 }
201}
202
203impl Img {
204 /// A list of all format extensions currently supported by this img element
205 pub fn extensions() -> &'static [&'static str] {
206 // This is the list in [image::ImageFormat::from_extension] + `svg`
207 &[
208 "avif", "jpg", "jpeg", "png", "gif", "webp", "tif", "tiff", "tga", "dds", "bmp", "ico",
209 "hdr", "exr", "pbm", "pam", "ppm", "pgm", "ff", "farbfeld", "qoi", "svg",
210 ]
211 }
212}
213
214impl Deref for Stateful<Img> {
215 type Target = Img;
216
217 fn deref(&self) -> &Self::Target {
218 &self.element
219 }
220}
221
222impl DerefMut for Stateful<Img> {
223 fn deref_mut(&mut self) -> &mut Self::Target {
224 &mut self.element
225 }
226}
227
228/// The image state between frames
229struct ImgState {
230 frame_index: usize,
231 last_frame_time: Option<Instant>,
232 started_loading: Option<(Instant, Task<()>)>,
233}
234
235/// The image layout state between frames
236pub struct ImgLayoutState {
237 frame_index: usize,
238 replacement: Option<AnyElement>,
239}
240
241impl Element for Img {
242 type RequestLayoutState = ImgLayoutState;
243 type PrepaintState = Option<Hitbox>;
244
245 fn id(&self) -> Option<ElementId> {
246 self.interactivity.element_id.clone()
247 }
248
249 fn request_layout(
250 &mut self,
251 global_id: Option<&GlobalElementId>,
252 window: &mut Window,
253 cx: &mut App,
254 ) -> (LayoutId, Self::RequestLayoutState) {
255 let mut layout_state = ImgLayoutState {
256 frame_index: 0,
257 replacement: None,
258 };
259
260 window.with_optional_element_state(global_id, |state, window| {
261 let mut state = state.map(|state| {
262 state.unwrap_or(ImgState {
263 frame_index: 0,
264 last_frame_time: None,
265 started_loading: None,
266 })
267 });
268
269 let frame_index = state.as_ref().map(|state| state.frame_index).unwrap_or(0);
270
271 let layout_id = self.interactivity.request_layout(
272 global_id,
273 window,
274 cx,
275 |mut style, window, cx| {
276 let mut replacement_id = None;
277
278 match self.source.use_data(window, cx) {
279 Some(Ok(data)) => {
280 if let Some(state) = &mut state {
281 let frame_count = data.frame_count();
282 if frame_count > 1 {
283 let current_time = Instant::now();
284 if let Some(last_frame_time) = state.last_frame_time {
285 let elapsed = current_time - last_frame_time;
286 let frame_duration =
287 Duration::from(data.delay(state.frame_index));
288
289 if elapsed >= frame_duration {
290 state.frame_index =
291 (state.frame_index + 1) % frame_count;
292 state.last_frame_time =
293 Some(current_time - (elapsed - frame_duration));
294 }
295 } else {
296 state.last_frame_time = Some(current_time);
297 }
298 }
299 state.started_loading = None;
300 }
301
302 let image_size = data.size(frame_index);
303
304 if let Length::Auto = style.size.width {
305 style.size.width = match style.size.height {
306 Length::Definite(DefiniteLength::Absolute(
307 AbsoluteLength::Pixels(height),
308 )) => Length::Definite(
309 px(image_size.width.0 as f32 * height.0
310 / image_size.height.0 as f32)
311 .into(),
312 ),
313 _ => Length::Definite(px(image_size.width.0 as f32).into()),
314 };
315 }
316
317 if let Length::Auto = style.size.height {
318 style.size.height = match style.size.width {
319 Length::Definite(DefiniteLength::Absolute(
320 AbsoluteLength::Pixels(width),
321 )) => Length::Definite(
322 px(image_size.height.0 as f32 * width.0
323 / image_size.width.0 as f32)
324 .into(),
325 ),
326 _ => Length::Definite(px(image_size.height.0 as f32).into()),
327 };
328 }
329
330 if global_id.is_some() && data.frame_count() > 1 {
331 window.request_animation_frame();
332 }
333 }
334 Some(_err) => {
335 if let Some(fallback) = self.style.fallback.as_ref() {
336 let mut element = fallback();
337 replacement_id = Some(element.request_layout(window, cx));
338 layout_state.replacement = Some(element);
339 }
340 if let Some(state) = &mut state {
341 state.started_loading = None;
342 }
343 }
344 None => {
345 if let Some(state) = &mut state {
346 if let Some((started_loading, _)) = state.started_loading {
347 if started_loading.elapsed() > LOADING_DELAY {
348 if let Some(loading) = self.style.loading.as_ref() {
349 let mut element = loading();
350 replacement_id =
351 Some(element.request_layout(window, cx));
352 layout_state.replacement = Some(element);
353 }
354 }
355 } else {
356 let parent_view_id = window.parent_view_id().unwrap();
357 let task = window.spawn(cx, |mut cx| async move {
358 cx.background_executor().timer(LOADING_DELAY).await;
359 cx.update(move |_, cx| {
360 cx.notify(parent_view_id);
361 })
362 .ok();
363 });
364 state.started_loading = Some((Instant::now(), task));
365 }
366 }
367 }
368 }
369
370 window.request_layout(style, replacement_id, cx)
371 },
372 );
373
374 layout_state.frame_index = frame_index;
375
376 ((layout_id, layout_state), state)
377 })
378 }
379
380 fn prepaint(
381 &mut self,
382 global_id: Option<&GlobalElementId>,
383 bounds: Bounds<Pixels>,
384 request_layout: &mut Self::RequestLayoutState,
385 window: &mut Window,
386 cx: &mut App,
387 ) -> Self::PrepaintState {
388 self.interactivity.prepaint(
389 global_id,
390 bounds,
391 bounds.size,
392 window,
393 cx,
394 |_, _, hitbox, window, cx| {
395 if let Some(replacement) = &mut request_layout.replacement {
396 replacement.prepaint(window, cx);
397 }
398
399 hitbox
400 },
401 )
402 }
403
404 fn paint(
405 &mut self,
406 global_id: Option<&GlobalElementId>,
407 bounds: Bounds<Pixels>,
408 layout_state: &mut Self::RequestLayoutState,
409 hitbox: &mut Self::PrepaintState,
410 window: &mut Window,
411 cx: &mut App,
412 ) {
413 let source = self.source.clone();
414 self.interactivity.paint(
415 global_id,
416 bounds,
417 hitbox.as_ref(),
418 window,
419 cx,
420 |style, window, cx| {
421 let corner_radii = style.corner_radii.to_pixels(bounds.size, window.rem_size());
422
423 if let Some(Ok(data)) = source.use_data(window, cx) {
424 let new_bounds = self
425 .style
426 .object_fit
427 .get_bounds(bounds, data.size(layout_state.frame_index));
428 window
429 .paint_image(
430 new_bounds,
431 corner_radii,
432 data.clone(),
433 layout_state.frame_index,
434 self.style.grayscale,
435 )
436 .log_err();
437 } else if let Some(replacement) = &mut layout_state.replacement {
438 replacement.paint(window, cx);
439 }
440 },
441 )
442 }
443}
444
445impl Styled for Img {
446 fn style(&mut self) -> &mut StyleRefinement {
447 &mut self.interactivity.base_style
448 }
449}
450
451impl InteractiveElement for Img {
452 fn interactivity(&mut self) -> &mut Interactivity {
453 &mut self.interactivity
454 }
455}
456
457impl IntoElement for Img {
458 type Element = Self;
459
460 fn into_element(self) -> Self::Element {
461 self
462 }
463}
464
465impl FocusableElement for Img {}
466
467impl StatefulInteractiveElement for Img {}
468
469impl ImageSource {
470 pub(crate) fn use_data(
471 &self,
472 window: &mut Window,
473 cx: &mut App,
474 ) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
475 match self {
476 ImageSource::Resource(resource) => window.use_asset::<ImgResourceLoader>(&resource, cx),
477 ImageSource::Custom(loading_fn) => loading_fn(window, cx),
478 ImageSource::Render(data) => Some(Ok(data.to_owned())),
479 ImageSource::Image(data) => window.use_asset::<AssetLogger<ImageDecoder>>(data, cx),
480 }
481 }
482}
483
484#[derive(Clone)]
485enum ImageDecoder {}
486
487impl Asset for ImageDecoder {
488 type Source = Arc<Image>;
489 type Output = Result<Arc<RenderImage>, ImageCacheError>;
490
491 fn load(
492 source: Self::Source,
493 cx: &mut App,
494 ) -> impl Future<Output = Self::Output> + Send + 'static {
495 let renderer = cx.svg_renderer();
496 async move { source.to_image_data(renderer).map_err(Into::into) }
497 }
498}
499
500/// An image loader for the GPUI asset system
501#[derive(Clone)]
502pub enum ImageAssetLoader {}
503
504impl Asset for ImageAssetLoader {
505 type Source = Resource;
506 type Output = Result<Arc<RenderImage>, ImageCacheError>;
507
508 fn load(
509 source: Self::Source,
510 cx: &mut App,
511 ) -> impl Future<Output = Self::Output> + Send + 'static {
512 let client = cx.http_client();
513 // TODO: Can we make SVGs always rescale?
514 // let scale_factor = cx.scale_factor();
515 let svg_renderer = cx.svg_renderer();
516 let asset_source = cx.asset_source().clone();
517 async move {
518 let bytes = match source.clone() {
519 Resource::Path(uri) => fs::read(uri.as_ref())?,
520 Resource::Uri(uri) => {
521 let mut response = client
522 .get(uri.as_ref(), ().into(), true)
523 .await
524 .map_err(|e| anyhow!(e))?;
525 let mut body = Vec::new();
526 response.body_mut().read_to_end(&mut body).await?;
527 if !response.status().is_success() {
528 let mut body = String::from_utf8_lossy(&body).into_owned();
529 let first_line = body.lines().next().unwrap_or("").trim_end();
530 body.truncate(first_line.len());
531 return Err(ImageCacheError::BadStatus {
532 uri,
533 status: response.status(),
534 body,
535 });
536 }
537 body
538 }
539 Resource::Embedded(path) => {
540 let data = asset_source.load(&path).ok().flatten();
541 if let Some(data) = data {
542 data.to_vec()
543 } else {
544 return Err(ImageCacheError::Asset(
545 format!("Embedded resource not found: {}", path).into(),
546 ));
547 }
548 }
549 };
550
551 let data = if let Ok(format) = image::guess_format(&bytes) {
552 let data = match format {
553 ImageFormat::Gif => {
554 let decoder = GifDecoder::new(Cursor::new(&bytes))?;
555 let mut frames = SmallVec::new();
556
557 for frame in decoder.into_frames() {
558 let mut frame = frame?;
559 // Convert from RGBA to BGRA.
560 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
561 pixel.swap(0, 2);
562 }
563 frames.push(frame);
564 }
565
566 frames
567 }
568 ImageFormat::WebP => {
569 let mut decoder = WebPDecoder::new(Cursor::new(&bytes))?;
570
571 if decoder.has_animation() {
572 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
573 let mut frames = SmallVec::new();
574
575 for frame in decoder.into_frames() {
576 let mut frame = frame?;
577 // Convert from RGBA to BGRA.
578 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
579 pixel.swap(0, 2);
580 }
581 frames.push(frame);
582 }
583
584 frames
585 } else {
586 let mut data = DynamicImage::from_decoder(decoder)?.into_rgba8();
587
588 // Convert from RGBA to BGRA.
589 for pixel in data.chunks_exact_mut(4) {
590 pixel.swap(0, 2);
591 }
592
593 SmallVec::from_elem(Frame::new(data), 1)
594 }
595 }
596 _ => {
597 let mut data =
598 image::load_from_memory_with_format(&bytes, format)?.into_rgba8();
599
600 // Convert from RGBA to BGRA.
601 for pixel in data.chunks_exact_mut(4) {
602 pixel.swap(0, 2);
603 }
604
605 SmallVec::from_elem(Frame::new(data), 1)
606 }
607 };
608
609 RenderImage::new(data)
610 } else {
611 let pixmap =
612 // TODO: Can we make svgs always rescale?
613 svg_renderer.render_pixmap(&bytes, SvgSize::ScaleFactor(1.0))?;
614
615 let mut buffer =
616 ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take()).unwrap();
617
618 for pixel in buffer.chunks_exact_mut(4) {
619 swap_rgba_pa_to_bgra(pixel);
620 }
621
622 RenderImage::new(SmallVec::from_elem(Frame::new(buffer), 1))
623 };
624
625 Ok(Arc::new(data))
626 }
627 }
628}
629
630/// An error that can occur when interacting with the image cache.
631#[derive(Debug, Error, Clone)]
632pub enum ImageCacheError {
633 /// Some other kind of error occurred
634 #[error("error: {0}")]
635 Other(#[from] Arc<anyhow::Error>),
636 /// An error that occurred while reading the image from disk.
637 #[error("IO error: {0}")]
638 Io(Arc<std::io::Error>),
639 /// An error that occurred while processing an image.
640 #[error("unexpected http status for {uri}: {status}, body: {body}")]
641 BadStatus {
642 /// The URI of the image.
643 uri: SharedUri,
644 /// The HTTP status code.
645 status: http_client::StatusCode,
646 /// The HTTP response body.
647 body: String,
648 },
649 /// An error that occurred while processing an asset.
650 #[error("asset error: {0}")]
651 Asset(SharedString),
652 /// An error that occurred while processing an image.
653 #[error("image error: {0}")]
654 Image(Arc<ImageError>),
655 /// An error that occurred while processing an SVG.
656 #[error("svg error: {0}")]
657 Usvg(Arc<usvg::Error>),
658}
659
660impl From<anyhow::Error> for ImageCacheError {
661 fn from(value: anyhow::Error) -> Self {
662 Self::Other(Arc::new(value))
663 }
664}
665
666impl From<io::Error> for ImageCacheError {
667 fn from(value: io::Error) -> Self {
668 Self::Io(Arc::new(value))
669 }
670}
671
672impl From<usvg::Error> for ImageCacheError {
673 fn from(value: usvg::Error) -> Self {
674 Self::Usvg(Arc::new(value))
675 }
676}
677
678impl From<image::ImageError> for ImageCacheError {
679 fn from(value: image::ImageError) -> Self {
680 Self::Image(Arc::new(value))
681 }
682}