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