Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Support animated WebP in `Image::to_image_data` (#66459)

Jorge635026fabc38
diff --git a/crates/gpui/src/elements/img.rs b/crates/gpui/src/elements/img.rs
index 2c77e5f32ad..a9878f4f70c 100644
--- a/crates/gpui/src/elements/img.rs
+++ b/crates/gpui/src/elements/img.rs
@@ -2,22 +2,18 @@ use crate::{
AnyElement, AnyImageCache, App, Asset, AssetLogger, Bounds, DefiniteLength, Element, ElementId,
Entity, GlobalElementId, Hitbox, Image, ImageCache, InspectorElementId, InteractiveElement,
Interactivity, IntoElement, LayoutId, Length, ObjectFit, Pixels, RenderImage, Resource,
- SharedString, SharedUri, StyleRefinement, Styled, Task, Window, decode_static_image,
- decode_static_image_from_decoder, px,
+ SharedString, SharedUri, StyleRefinement, Styled, Task, Window, decode_gif_image,
+ decode_static_image, decode_webp_image, px,
};
use anyhow::Result;
use futures::Future;
use gpui_util::ResultExt;
-use image::{
- AnimationDecoder, ImageError, ImageFormat, Rgba,
- codecs::{gif::GifDecoder, webp::WebPDecoder},
-};
+use image::{ImageError, ImageFormat};
use scheduler::Instant;
-use smallvec::SmallVec;
use std::{
fs,
- io::{self, Cursor},
+ io::{self},
ops::{Deref, DerefMut},
path::{Path, PathBuf},
str::FromStr,
@@ -668,70 +664,8 @@ impl Asset for ImageAssetLoader {
if let Ok(format) = image::guess_format(&bytes) {
let data = match format {
- ImageFormat::Gif => {
- let decoder = GifDecoder::new(Cursor::new(&bytes))?;
- let mut frames = SmallVec::new();
-
- for frame in decoder.into_frames() {
- match frame {
- Ok(mut frame) => {
- // Convert from RGBA to BGRA.
- for pixel in frame.buffer_mut().chunks_exact_mut(4) {
- pixel.swap(0, 2);
- }
- frames.push(frame);
- }
- Err(err) => {
- log::debug!(
- "Skipping GIF frame in {source:?} due to decode error: {err}"
- );
- }
- }
- }
-
- if frames.is_empty() {
- return Err(ImageCacheError::Other(Arc::new(anyhow::anyhow!(
- "GIF could not be decoded: all frames failed ({source:?})"
- ))));
- }
-
- frames
- }
- ImageFormat::WebP => {
- let mut decoder = WebPDecoder::new(Cursor::new(&bytes))?;
-
- if decoder.has_animation() {
- let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
- let mut frames = SmallVec::new();
-
- for frame in decoder.into_frames() {
- match frame {
- Ok(mut frame) => {
- // Convert from RGBA to BGRA.
- for pixel in frame.buffer_mut().chunks_exact_mut(4) {
- pixel.swap(0, 2);
- }
- frames.push(frame);
- }
- Err(err) => {
- log::debug!(
- "Skipping WebP frame in {source:?} due to decode error: {err}"
- );
- }
- }
- }
-
- if frames.is_empty() {
- return Err(ImageCacheError::Other(Arc::new(anyhow::anyhow!(
- "WebP could not be decoded: all frames failed ({source:?})"
- ))));
- }
-
- frames
- } else {
- decode_static_image_from_decoder(decoder)?
- }
- }
+ ImageFormat::Gif => decode_gif_image(&bytes)?,
+ ImageFormat::WebP => decode_webp_image(&bytes)?,
_ => decode_static_image(&bytes, format)?,
};
@@ -804,6 +738,7 @@ mod tests {
use super::*;
use crate::{ParentElement as _, TestAppContext, canvas, div, point, px, size};
use image::{Frame, ImageBuffer, Rgba};
+ use smallvec::SmallVec;
const TEST_IMG_ID: &str = "test-img";
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index 6ddbac4c432..b84bcc5c092 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -53,8 +53,8 @@ use collections::FxHashMap;
use futures::channel::oneshot;
#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
use image::RgbaImage;
-use image::codecs::gif::GifDecoder;
-use image::{AnimationDecoder as _, DynamicImage, Frame};
+use image::codecs::{gif::GifDecoder, webp::WebPDecoder};
+use image::{DynamicImage, Frame, Rgba};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use scheduler::Instant;
pub use scheduler::RunnableMeta;
@@ -3387,6 +3387,50 @@ pub(crate) fn decode_static_image_from_decoder(
Ok(SmallVec::from_elem(Frame::new(data), 1))
}
+fn decode_animated_frames<'a>(
+ decoder: impl image::AnimationDecoder<'a>,
+ format_name: &str,
+) -> Result<SmallVec<[Frame; 1]>> {
+ let mut frames = SmallVec::new();
+
+ for frame in decoder.into_frames() {
+ match frame {
+ Ok(mut frame) => {
+ // Convert from RGBA to BGRA.
+ for pixel in frame.buffer_mut().chunks_exact_mut(4) {
+ pixel.swap(0, 2);
+ }
+ frames.push(frame);
+ }
+ Err(err) => {
+ log::debug!("Skipping {format_name} frame due to decode error: {err}");
+ }
+ }
+ }
+
+ if frames.is_empty() {
+ anyhow::bail!("{format_name} could not be decoded: all frames failed");
+ }
+
+ Ok(frames)
+}
+
+pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
+ let decoder = GifDecoder::new(Cursor::new(bytes))?;
+ decode_animated_frames(decoder, "GIF")
+}
+
+pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
+ let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
+
+ if decoder.has_animation() {
+ let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
+ decode_animated_frames(decoder, "WebP")
+ } else {
+ decode_static_image_from_decoder(decoder)
+ }
+}
+
impl Hash for Image {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u64(self.id);
@@ -3450,34 +3494,10 @@ impl Image {
/// Convert the clipboard image to an `ImageData` object.
pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
let frames = match self.format {
- ImageFormat::Gif => {
- let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
- let mut frames = SmallVec::new();
-
- for frame in decoder.into_frames() {
- match frame {
- Ok(mut frame) => {
- // Convert from RGBA to BGRA.
- for pixel in frame.buffer_mut().chunks_exact_mut(4) {
- pixel.swap(0, 2);
- }
- frames.push(frame);
- }
- Err(err) => {
- log::debug!("Skipping GIF frame due to decode error: {err}");
- }
- }
- }
-
- if frames.is_empty() {
- anyhow::bail!("GIF could not be decoded: all frames failed");
- }
-
- frames
- }
+ ImageFormat::Gif => decode_gif_image(&self.bytes)?,
ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
- ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
+ ImageFormat::Webp => decode_webp_image(&self.bytes)?,
ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
@@ -3604,6 +3624,36 @@ mod image_tests {
assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
}
}
+
+ #[test]
+ fn test_animated_webp_image_to_image_data_decodes_frames() {
+ // 1x1 2-frame animated WebP (frame 0: red, frame 1: blue, 100ms delay each).
+ const ANIMATED_WEBP: &[u8] = &[
+ 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
+ 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 2, 86, 80, 56, 32, 48, 0,
+ 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
+ 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
+ 128, 255, 248, 242, 0, 0, 0, 65, 78, 77, 70, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 100, 0, 0, 0, 86, 80, 56, 32, 44, 0, 0, 0, 148, 1, 0, 157, 1, 42, 1, 0, 1, 0, 0,
+ 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
+ 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
+ ];
+
+ let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
+ let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
+
+ assert_eq!(render_image.frame_count(), 2);
+ assert_eq!(render_image.size(0), size(1.into(), 1.into()));
+ assert_eq!(
+ Duration::from(render_image.delay(0)),
+ Duration::from_millis(100)
+ );
+ assert_eq!(
+ Duration::from(render_image.delay(1)),
+ Duration::from_millis(100)
+ );
+ }
}
#[cfg(test)]