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