BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / emoticons / strip.rs

strip.rs

strip.rs 3.6 KiB Download Raw
1use std::io::Cursor;
2use std::sync::Arc;
3use std::time::Duration;
4
5use gpui_kit::{App, Asset, ImageCacheError, RenderImage, SharedUri};
6use image::{Delay, Frame, ImageFormat, RgbaImage};
7
8#[derive(Debug, Clone, PartialEq, Eq, Hash)]
9pub struct StripSource {
10 pub url: SharedUri,
11 pub frame_duration: Duration,
12}
13
14pub struct StripImages {
15 pub animated: Arc<RenderImage>,
16 pub still: Arc<RenderImage>,
17}
18
19pub enum StripLoader {}
20
21impl Asset for StripLoader {
22 type Source = StripSource;
23 type Output = Result<Arc<StripImages>, ImageCacheError>;
24
25 fn load(
26 source: Self::Source,
27 cx: &mut App,
28 ) -> impl Future<Output = Self::Output> + Send + 'static {
29 let client = cx.http_client();
30 async move {
31 use futures_util::AsyncReadExt as _;
32 let mut response = client.get(source.url.as_ref(), ().into(), true).await?;
33 let mut body = Vec::new();
34 response.body_mut().read_to_end(&mut body).await?;
35 if !response.status().is_success() {
36 return Err(ImageCacheError::BadStatus {
37 uri: source.url,
38 status: response.status(),
39 body: String::new(),
40 });
41 }
42 let frames = split_strip(&body, source.frame_duration)?;
43 let still = RenderImage::new(frames[..1].to_vec());
44 Ok(Arc::new(StripImages {
45 animated: Arc::new(RenderImage::new(frames)),
46 still: Arc::new(still),
47 }))
48 }
49 }
50}
51
52pub fn split_strip(
53 bytes: &[u8],
54 frame_duration: Duration,
55) -> Result<Vec<Frame>, image::ImageError> {
56 let strip = image::load(Cursor::new(bytes), ImageFormat::Png)?.into_rgba8();
57 let side = strip.width().max(1);
58 let count = (strip.height() / side).max(1);
59 let delay = Delay::from_saturating_duration(frame_duration);
60 Ok((0..count)
61 .map(|index| {
62 let mut frame: RgbaImage =
63 image::imageops::crop_imm(&strip, 0, index * side, side, side.min(strip.height()))
64 .to_image();
65 for pixel in frame.chunks_exact_mut(4) {
66 pixel.swap(0, 2);
67 }
68 Frame::from_parts(frame, 0, 0, delay)
69 })
70 .collect())
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use image::{DynamicImage, Rgba};
77
78 fn strip(side: u32, colors: &[[u8; 3]]) -> Vec<u8> {
79 let mut image = RgbaImage::new(side, side * colors.len() as u32);
80 for (index, color) in colors.iter().enumerate() {
81 for y in 0..side {
82 for x in 0..side {
83 image.put_pixel(
84 x,
85 index as u32 * side + y,
86 Rgba([color[0], color[1], color[2], 255]),
87 );
88 }
89 }
90 }
91 let mut bytes = Vec::new();
92 DynamicImage::ImageRgba8(image)
93 .write_to(&mut Cursor::new(&mut bytes), ImageFormat::Png)
94 .unwrap();
95 bytes
96 }
97
98 #[test]
99 fn a_strip_splits_into_square_bgra_frames_with_the_given_delay() {
100 let bytes = strip(4, &[[255, 0, 0], [0, 255, 0], [0, 0, 255]]);
101 let frames = split_strip(&bytes, Duration::from_millis(40)).unwrap();
102 assert_eq!(frames.len(), 3);
103 assert_eq!(frames[0].buffer().dimensions(), (4, 4));
104 assert_eq!(frames[0].buffer().get_pixel(0, 0).0, [0, 0, 255, 255]);
105 assert_eq!(frames[2].buffer().get_pixel(3, 3).0, [255, 0, 0, 255]);
106 assert_eq!(Duration::from(frames[1].delay()), Duration::from_millis(40));
107 }
108}