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