BlueGit

ict rusty-teams

Files

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

avatar_image.rs

avatar_image.rs 8.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
100/// Microsoft's small profile photos often carry a light outer row or column; the disc touches it at the edge midpoints.
101const EDGE_TRIM_PER: u32 = 48;
102
103pub fn square_texture(bytes: &[u8], side: u32) -> Option<RgbaImage> {
104 let decoded = image::load_from_memory(bytes).ok()?.to_rgba8();
105 let full = decoded.width().min(decoded.height());
106 let trim = if full > 2 {
107 (full / EDGE_TRIM_PER).max(1)
108 } else {
109 0
110 };
111 let crop = full - 2 * trim;
112 let left = (decoded.width() - full) / 2 + trim;
113 let top = (decoded.height() - full) / 2 + trim;
114 let square = image::imageops::crop_imm(&decoded, left, top, crop, crop).to_image();
115 let mut texture = if crop == side {
116 square
117 } else {
118 image::imageops::resize(&square, side, side, FilterType::Lanczos3)
119 };
120 for pixel in texture.pixels_mut() {
121 pixel.0.swap(0, 2);
122 }
123 Some(texture)
124}
125
126#[cfg(test)]
127mod tests {
128 use image::Rgba;
129
130 use super::*;
131
132 fn solid_jpeg(width: u32, height: u32) -> Vec<u8> {
133 let source = RgbaImage::from_pixel(width, height, Rgba([200, 100, 50, 255]));
134 let mut encoded = Vec::new();
135 image::DynamicImage::ImageRgba8(source)
136 .to_rgb8()
137 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Jpeg)
138 .unwrap();
139 encoded
140 }
141
142 #[test]
143 fn texture_matches_the_device_pixels_and_is_bgra() {
144 let texture = square_texture(&solid_jpeg(240, 240), 39).unwrap();
145 assert_eq!(texture.dimensions(), (39, 39));
146 let Rgba([blue, _, red, alpha]) = *texture.get_pixel(19, 19);
147 assert!(
148 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
149 "{blue} {red}"
150 );
151 assert_eq!(alpha, 255);
152 }
153
154 #[test]
155 fn the_margin_repeats_the_edge_texels() {
156 let mut texture = RgbaImage::from_pixel(3, 3, Rgba([1, 2, 3, 255]));
157 texture.put_pixel(0, 0, Rgba([9, 9, 9, 255]));
158 let padded = with_edge_margin(&texture, 2);
159 assert_eq!(padded.dimensions(), (7, 7));
160 assert_eq!(*padded.get_pixel(0, 0), Rgba([9, 9, 9, 255]));
161 assert_eq!(*padded.get_pixel(1, 2), Rgba([9, 9, 9, 255]));
162 assert_eq!(*padded.get_pixel(6, 6), Rgba([1, 2, 3, 255]));
163 }
164
165 #[test]
166 fn a_light_outer_edge_of_the_photo_is_trimmed() {
167 let mut source = RgbaImage::from_pixel(48, 48, Rgba([40, 40, 40, 255]));
168 for index in 0..48 {
169 source.put_pixel(index, 0, Rgba([255, 255, 255, 255]));
170 source.put_pixel(47, index, Rgba([255, 255, 255, 255]));
171 }
172 let mut encoded = Vec::new();
173 image::DynamicImage::ImageRgba8(source)
174 .write_to(&mut Cursor::new(&mut encoded), ImageFormat::Png)
175 .unwrap();
176 let texture = square_texture(&encoded, 32).unwrap();
177 let Rgba([top, ..]) = *texture.get_pixel(16, 0);
178 let Rgba([right, ..]) = *texture.get_pixel(31, 16);
179 assert!(top < 80 && right < 80, "top {top}, right {right}");
180 }
181
182 #[test]
183 fn non_square_photos_are_center_cropped() {
184 assert_eq!(
185 square_texture(&solid_jpeg(64, 40), 60)
186 .unwrap()
187 .dimensions(),
188 (60, 60)
189 );
190 }
191
192 #[test]
193 fn device_span_follows_the_snapped_bounds() {
194 assert_eq!(device_span(0., 26., 1.), 26);
195 assert_eq!(device_span(0., 28., 1.5), 42);
196 assert_eq!(device_span(10.5, 36.5, 1.5), 39);
197 assert_eq!(device_span(10.1, 36.1, 1.5), 39);
198 assert_eq!(device_span(0., 32., 1.25), 40);
199 assert_eq!(device_span(0., 0.1, 1.), 1);
200 assert_eq!(device_span(-3.5, 22.5, 1.), 25);
201 }
202
203 #[test]
204 fn textures_are_cached_per_side_and_evict_the_oldest() {
205 let photo = AvatarPhoto::from_bytes(solid_jpeg(48, 48)).unwrap();
206 let first = photo.texture(32).unwrap();
207 let again = photo.texture(32).unwrap();
208 assert_eq!(first.image.id, again.image.id);
209 assert!(again.evicted.is_none());
210 for side in 33..33 + MAX_TEXTURES as u32 - 1 {
211 assert!(photo.texture(side).unwrap().evicted.is_none());
212 }
213 let overflow = photo.texture(100).unwrap();
214 assert_eq!(overflow.evicted.map(|image| image.id), Some(first.image.id));
215 }
216
217 #[test]
218 fn large_originals_are_kept_at_the_source_side() {
219 let photo = AvatarPhoto::from_bytes(solid_jpeg(1200, 900)).unwrap();
220 let dimensions = image::load_from_memory(&photo.bytes)
221 .unwrap()
222 .to_rgba8()
223 .dimensions();
224 assert_eq!(dimensions, (SOURCE_SIDE, SOURCE_SIDE));
225 let texture = photo.texture(20).unwrap().image;
226 let raw = texture.as_bytes(0).unwrap().to_vec();
227 let padded_side = 20 + 2 * TEXTURE_MARGIN;
228 let Rgba([blue, _, red, _]) = *RgbaImage::from_raw(padded_side, padded_side, raw)
229 .unwrap()
230 .get_pixel(10, 10);
231 assert!(
232 blue.abs_diff(50) <= 3 && red.abs_diff(200) <= 3,
233 "{blue} {red}"
234 );
235 }
236
237 #[test]
238 fn garbage_bytes_fall_back() {
239 assert!(AvatarPhoto::from_bytes(b"not an image".to_vec()).is_none());
240 }
241}