BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / avatar_image.rs

avatar_image.rs

avatar_image.rs 7.1 KiB Download Raw
1use std::io::Cursor;
2use std::sync::{Arc, Mutex};
3
4use gpui_kit::RenderImage;
5use image::imageops::FilterType;
6use image::{Frame, ImageFormat, ImageReader, RgbaImage};
7
8const MAX_TEXTURES: usize = 8;
9const SOURCE_SIDE: u32 = 240;
10const SOURCE_LIMIT: u32 = 2 * SOURCE_SIDE;
11pub const TEXTURE_MARGIN: u32 = 2;
12
13pub struct AvatarPhoto {
14 bytes: Vec<u8>,
15 textures: Mutex<Vec<(u32, Arc<RenderImage>)>>,
16}
17
18pub struct Texture {
19 pub image: Arc<RenderImage>,
20 pub evicted: Option<Arc<RenderImage>>,
21}
22
23impl AvatarPhoto {
24 pub fn source_bytes(&self) -> &[u8] {
25 &self.bytes
26 }
27
28 pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
29 let (width, height) = ImageReader::new(Cursor::new(&bytes))
30 .with_guessed_format()
31 .ok()?
32 .into_dimensions()
33 .ok()?;
34 if width == 0 || height == 0 {
35 return None;
36 }
37 let bytes = if width.max(height) > SOURCE_LIMIT {
38 shrunk_source(&bytes)?
39 } else {
40 bytes
41 };
42 Some(Self {
43 bytes,
44 textures: Mutex::new(Vec::new()),
45 })
46 }
47
48 pub fn texture(&self, side: u32) -> Option<Texture> {
49 let mut textures = self.textures.lock().ok()?;
50 if let Some(position) = textures.iter().position(|(cached, _)| *cached == side) {
51 let entry = textures.remove(position);
52 let image = entry.1.clone();
53 textures.push(entry);
54 return Some(Texture {
55 image,
56 evicted: None,
57 });
58 }
59 let pixels = with_edge_margin(&square_texture(&self.bytes, side)?, TEXTURE_MARGIN);
60 let image = Arc::new(RenderImage::new(vec![Frame::new(pixels)]));
61 let evicted = (textures.len() >= MAX_TEXTURES).then(|| textures.remove(0).1);
62 textures.push((side, image.clone()));
63 Some(Texture { image, evicted })
64 }
65}
66
67fn shrunk_source(bytes: &[u8]) -> Option<Vec<u8>> {
68 let mut source = square_texture(bytes, SOURCE_SIDE)?;
69 for pixel in source.pixels_mut() {
70 pixel.0.swap(0, 2);
71 }
72 let mut encoded = Vec::new();
73 source
74 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
75 .ok()?;
76 Some(encoded)
77}
78
79pub fn device_span(start: f32, end: f32, scale_factor: f32) -> u32 {
80 let snapped =
81 round_half_toward_zero(end * scale_factor) - round_half_toward_zero(start * scale_factor);
82 snapped.max(1.) as u32
83}
84
85fn round_half_toward_zero(value: f32) -> f32 {
86 value.signum() * (value.abs() - 0.5).ceil()
87}
88
89/// The sprite atlas packs images without gaps and samples linearly, so the outer texels
90/// of a photo blend with its neighbour. Repeated edge texels keep that blend inside the photo.
91pub fn with_edge_margin(texture: &RgbaImage, margin: u32) -> RgbaImage {
92 let (width, height) = texture.dimensions();
93 RgbaImage::from_fn(width + 2 * margin, height + 2 * margin, |x, y| {
94 let source_x = x.saturating_sub(margin).min(width - 1);
95 let source_y = y.saturating_sub(margin).min(height - 1);
96 *texture.get_pixel(source_x, source_y)
97 })
98}
99
100pub fn square_texture(bytes: &[u8], side: u32) -> Option<RgbaImage> {
101 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
102 let crop = decoded.width().min(decoded.height());
103 let left = (decoded.width() - crop) / 2;
104 let top = (decoded.height() - crop) / 2;
105 let square = image::imageops::crop_imm(&decoded, left, top, crop, crop).to_image();
106 let mut texture = if crop == side {
107 square
108 } else {
109 image::imageops::resize(&square, side, side, FilterType::Lanczos3)
110 };
111 for pixel in texture.pixels_mut() {
112 pixel.0.swap(0, 2);
113 }
114 Some(texture)
115}
116
117#[cfg(test)]
118mod tests {
119 use image::Rgba;
120
121 use super::*;
122
123 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
124 let source = RgbaImage::from_pixel(width, height, Rgba([200, 100, 50, 255]));
125 let mut encoded = Vec::new();
126 image::DynamicImage::ImageRgba8(source)
127 .to_rgb8()
128 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Jpeg)
129 .unwrap();
130 encoded
131 }
132
133 #[test]
134 fn texture_matches_the_device_pixels_and_is_bgra() {
135 let texture = square_texture(&solid_jpeg(240, 240), 39).unwrap();
136 assert_eq!(texture.dimensions(), (39, 39));
137 let Rgba([blue, _, red, alpha]) = *texture.get_pixel(19, 19);
138 assert!(
139 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
140 "{blue} {red}"
141 );
142 assert_eq!(alpha, 255);
143 }
144
145 #[test]
146 fn the_margin_repeats_the_edge_texels() {
147 let mut texture = RgbaImage::from_pixel(3, 3, Rgba([1, 2, 3, 255]));
148 texture.put_pixel(0, 0, Rgba([9, 9, 9, 255]));
149 let padded = with_edge_margin(&texture, 2);
150 assert_eq!(padded.dimensions(), (7, 7));
151 assert_eq!(*padded.get_pixel(0, 0), Rgba([9, 9, 9, 255]));
152 assert_eq!(*padded.get_pixel(1, 2), Rgba([9, 9, 9, 255]));
153 assert_eq!(*padded.get_pixel(6, 6), Rgba([1, 2, 3, 255]));
154 }
155
156 #[test]
157 fn non_square_photos_are_center_cropped() {
158 assert_eq!(
159 square_texture(&solid_jpeg(64, 40), 60)
160 .unwrap()
161 .dimensions(),
162 (60, 60)
163 );
164 }
165
166 #[test]
167 fn device_span_follows_the_snapped_bounds() {
168 assert_eq!(device_span(0., 26., 1.), 26);
169 assert_eq!(device_span(0., 28., 1.5), 42);
170 assert_eq!(device_span(10.5, 36.5, 1.5), 39);
171 assert_eq!(device_span(10.1, 36.1, 1.5), 39);
172 assert_eq!(device_span(0., 32., 1.25), 40);
173 assert_eq!(device_span(0., 0.1, 1.), 1);
174 assert_eq!(device_span(-3.5, 22.5, 1.), 25);
175 }
176
177 #[test]
178 fn textures_are_cached_per_side_and_evict_the_oldest() {
179 let photo = AvatarPhoto::from_bytes(solid_jpeg(48, 48)).unwrap();
180 let first = photo.texture(32).unwrap();
181 let again = photo.texture(32).unwrap();
182 assert_eq!(first.image.id, again.image.id);
183 assert!(again.evicted.is_none());
184 for side in 33..33 + MAX_TEXTURES as u32 - 1 {
185 assert!(photo.texture(side).unwrap().evicted.is_none());
186 }
187 let overflow = photo.texture(100).unwrap();
188 assert_eq!(overflow.evicted.map(|image| image.id), Some(first.image.id));
189 }
190
191 #[test]
192 fn large_originals_are_kept_at_the_source_side() {
193 let photo = AvatarPhoto::from_bytes(solid_jpeg(1200, 900)).unwrap();
194 let dimensions = image::load_from_memory(&photo.bytes)
195 .unwrap()
196 .to_rgba8()
197 .dimensions();
198 assert_eq!(dimensions, (SOURCE_SIDE, SOURCE_SIDE));
199 let texture = photo.texture(20).unwrap().image;
200 let raw = texture.as_bytes(0).unwrap().to_vec();
201 let padded_side = 20 + 2 * TEXTURE_MARGIN;
202 let Rgba([blue, _, red, _]) = *RgbaImage::from_raw(padded_side, padded_side, raw)
203 .unwrap()
204 .get_pixel(10, 10);
205 assert!(
206 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
207 "{blue} {red}"
208 );
209 }
210
211 #[test]
212 fn garbage_bytes_fall_back() {
213 assert!(AvatarPhoto::from_bytes(b"not an image".to_vec()).is_none());
214 }
215}